Inserting text gives objectcollection error

后端 未结 4 2048
终归单人心
终归单人心 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 01:54

    Try this

    comboBox1.Items.Insert(index, dr.GetString(1) + dr.GetString(2));
    

    Where index is an integer value where you want to insert in combobox

    Did you mean this

    comboBox1.Items.Insert(dr.GetInt32(0), dr.GetString(1) + dr.GetString(2));
    

    If you want to just add in combobox try the following

    comboBox1.Items.Add(dr.GetString(1) + dr.GetString(2));
    

    I think you're looking for DataSource

    void comboboxrefresh()
    {
        cnn.Open();
        SqlCommand cmd = new SqlCommand("SELECT EmployeeID, (EmployeeFirstName + EmployeeLastName) as EmployeeName FROM Employees", cnn);
        DataTable table = new Datatable();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(table);
    
        comboBox1.DisplayMember = "EmployeeName";
        comboBox1.ValueMember = "EmployeeID";
    
        comboBox1.DataSource = table;
    
        cnn.Close();
    }
    

提交回复
热议问题