Home>

winforms application, combobox-y on collections needs to pull one column from the database. I tried it myself using numerous sources, I managed to display something in a combobox. when you click on one of the displayed items, the data in the combobox is doubled. tried combobox1.Items.Clear(); then no data is retrieved at all. please help me figure it out.

private void LoadData() //output method on combobox
    {
        con.Open();
        var command= new MySql.Data.MySqlClient.MySqlCommand();
        command.Connection= con;
        command.CommandType= CommandType.Text;
        command.CommandText= "SELECT dslam FROM Sumdslam";
       //con.Close();
        var adapter= new MySql.Data.MySqlClient.MySqlDataAdapter(command);
        var dataset= new DataSet();
        adapter.Fill(dataset);
        DataTable dt= dataset.Tables[0];
        for (int i= 0; i < dataset.Tables[0].Rows.Count; i++)
         {
             combobox1.Items.Add(dataset.Tables[0].Rows[i][0].ToString());
             con.Close();
         }
      private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
       {
        //combobox1.SelectedIndex.ToString();
        LoadData();
        //combobox1.Items.Clear();
    }

if clear the contents of combobox1 via clear then the row is not selected at all, i.e. I have to select one element from there with all the data entered above should be added. if you do not clear the contents of the combobox then there is a doubling.

Mister junior2022-01-14 08:14:39

If I understand correctly, now the LoadData method is called every time you change the selected element in the Combobox -hence the doubles. The line combobox1.Items.Clear(); must appear before the call to the LoadData method. When populating the list, you close the db connection after accessing the first value in the db, wrap con.Close(); out of loop -when the loop completes its work.

Сергей Татевосян2022-01-14 08:15:26

yes, LoadData is called when another database table changes. if you clear the contents of the combobox nothing from the selection is simple

Mister junior2022-01-14 08:19:05

Your Combobox is cleared after calling LoadData, do the cleanup before calling the fill method.

Сергей Татевосян2022-01-14 08:22:36

did , nothing changes, splitting does not occur, but you can not select an element from the combobox. strange, why is this happening?

Mister junior2022-01-14 08:23:44
c#