I have a checkedlistbox that is being generated by a datatable at form load. It contains a list of author names as my form is about adding books. A single book could have one or more authors, so that is the case.

What it must do is when I add a book and there is two author name checked, then it will store in my database which will give two rows, same book title but different author.

I assume that it needs a for loop. This is my line of code for the checkedlistbox.

cmd.Parameters.Add("@authorname", SqlDbType.NVarChar).Value = authorclb.SelectedItem;
foreach (String author in authorclb.SelectedItems) {
    ... your insert here
}

It doesn't work. It just get one value

foreach (string @authorname in authorclb.SelectedItems)
                {
                    cmd.Parameters.Add("@authorname", SqlDbType.NVarChar).Value = authorclb.SelectedItem;
                }

you should perform multiple INSERT since the data is a seperate record to be added to the database

Record 1: Book 1, Author 1
Record 2: Book 1, Author 2

foreach (string @authorname in authorclb.SelectedItems)
{
   cmd.Parameter.Add("@bookname", SqlDbType.NvarChar).Value = BookName;
   cmd.Parameter.Add("@authorname", SqlDbType.NvarChar).Value = authorclb.SelectedItem;

   //then execute your INSERT query
}

It's not a separate record. It will be add to the same table just like the book.

It's not a separate record. It will be add to the same table just like the book.

- are you going to save it in one 1 record then insert it to your table in your database?

I already have an insert query above for adding that but you said that I will again put an insert query.

insert into BookTbl values (booktitle, authorname)

Why is that?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.