Inserting text gives objectcollection error

后端 未结 4 2031
终归单人心
终归单人心 2021-01-29 01:10

I want to insert each row in SQL into combobox, where EmployeeID will be combobox Value, and EmployeeFirstName EmployeeLastName will be text of combobox item. However this line<

4条回答
  •  灰色年华
    2021-01-29 02:00

    First, use Add to add items to the ComboBox. Second, I prefer anonymous type to fill the ComboBox while you use plain native Sql and simple DataReader immediately inside your form.

    void comboboxrefresh()
        {
            cnn.Open();
            SqlCommand cmd = new SqlCommand("SELECT EmployeeID,EmployeeFirstName,EmployeeLastName FROM Employees", cnn);
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                combobox1.ValueMember = "Id";
                combobox1.DisplayMember = "FullName";
    
                while (dr.Read())
                {
                    comboBox1.Items.Add(
                      new {
                             FullName = dr.GetString(1) + " " + dr.GetString(2), 
                             Id = dr.GetInt32(0)
                          });
                }
            }
    
            cnn.Close();
        }
    

    Update:

    I noticed that naively adding to the Item list is not working! Instead, DataSource property of ComboBox should be set to desired list. So the working code is as:

    var list = new List();
    combobox1.ValueMember = "Id";
    combobox1.DisplayMember = "FullName";
    while (dr.Read())
    {
       list.Add(
           new {
                  FullName = dr.GetString(1) + " " + dr.GetString(2), 
                  Id = dr.GetInt32(0)
                });
     }
    combobox1.DataSource = list;
    
        

    提交回复
    热议问题