Search code examples
c#listboxselectedindex

C# listBox.SelectedIndex from Database


In visual Studio 2010 (using visual C#),I have a form where there is a listBox (named listBox1). The user selects one of the items displayed on the listBox and then clicks on a Save Button. The application saves the user's selection into a Database using:

cmd.CommandText = "insert into Table2 (kat) values ('"+listBox1.SelectedIndex.ToString()+"')"

(edit)For instance they are saved as 0 or 1 or 2 etc...

And then I want the application to use that int to select the same item on another listBox,with the exactly same items but on another form.

What I have so far is:

cmd.CommandText = "select * from Table1 WHERE username='"+textBox1.Text+"'";
                                dr = cmd.ExecuteReader();
                                if (dr.HasRows)
                                {
                                    while (dr.Read())
                                    {
                                        form1.listBox1.SelectedIndex(dr[0]);
                                    }

                                }

Solution

  • You are inserting value as String in the database, and then trying to add values as Integer the wrong way

    to properly insert value as integer

    cmd.CommandText = "INSERT INTO Table1(kat) VALUES(@id)";
    cmd.Parameters.AddWithValue("@id", listBox1.SelectedIndex);
    cmd.ExecuteNonQuery();
    

    The to create the copy of the listBox on other form you can do so by using a SELECT query.

    Ex.

    cmd.CommandText = "SELECT kat FROM Table1";
    
    var reader = cmd.ExecuteReader();
    
    while(reader.Read())
    {
        otherListBox.Items.Add(reader[0]);
    }
    reader.Close();
    

    To sync the list , try this

    int index = listBox1.FindStringExact("id to find");
    
    if (index > -1)
    {
        listBox1.SelectedIndex = index;
    }