Anita Mathew
Anita Mathew

Reputation: 183

How to update multiple selections of a listbox, in different rows of a nvarchar() column in database?

I have a dropdowncheckbox consisting of several userid's. Now on selecting a user it will display 2 listboxes, Listbox1 has a list of barcodes and Listbox2 contains barcodes already assigned to the user. From listbox1 multiple items need to be selected and assigned to the user.Now I want to update the selected userid column against the selected barcodes. Each barcode is in a different row in the database . I tried:

protected void assign_Click(object sender, EventArgs e)
{
    try
    {
        if (ListBox1.SelectedIndex == -1)
        {
            Label9.Text = "Please Select Barcodes";
        }
        else
        {
            foreach (ListItem item in ListBox1.Items)
            {
                if (item.Selected == true)
                {
                    ListBox2.Items.Add(item);
                    ListBox1.Items.Remove(ListBox1.SelectedItem);
                }
            }

        }
    }
    catch { //Some code }
    finally
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);

        string cmdtxt= "Update " + con.Database + " set AssgnId= @userid where barcode= @barcode ";

        SqlCommand cmd = new SqlCommand(cmdtxt,con);
        cmd.Parameters.AddWithValue("@userid", ddchkteachers2.SelectedItem.Value);
        cmd.Parameters.AddWithValue("@barcode", ListBox1.SelectedItem);

        con.Open();

        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected == true)
            {
                cmd.Parameters["@barcode"].Value = Convert.ToString(ListBox1.SelectedItem);
                cmd.ExecuteNonQuery();
            }
        } 
        con.Close();
    }
}

The selected barcodes are in a nvarchar()column in the database. How to convert? the current value in the userid column against the barcodes are Null. Code does'nt update .

Upvotes: 2

Views: 429

Answers (1)

M. Adeel Khalid
M. Adeel Khalid

Reputation: 1796

You are removing Items from ListBox1 in first loop by checking whether they are selected or not and in the second loop you are doing same thing. It means there will be no value within your ListBox1 within 2nd loop. You can put a breakpoint within the loop and verify its values.

When the statement executes,

cmd.Parameters.AddWithValue("@barcode", ListBox1.SelectedItem);

There is nothing within your ListBox1.SelectedItem, same is the case within your foreach loop. Hope it helps.

Upvotes: 1

Related Questions