插入文本会导致objectcollection错误

时间:2013-09-27 19:19:41

标签: c# combobox

我想将SQL中的每一行插入到组合框中,其中EmployeeID将是组合框值,而EmployeeFirstName EmployeeLastName将是组合框项目的文本。不过这一行

给了我这个错误:

  

错误1'System.Windows.Forms.ComboBox.ObjectCollection.Insert(int,object)'的最佳重载方法匹配   有一些无效的   参数C:\ Users \ bilgisayar \ Desktop \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Form1.cs 45 21 WindowsFormsApplication1

4 个答案:

答案 0 :(得分:2)

定义一个新类

public class EmpItem
{
   public int empID;
   public string empName;
}  

在阅读DataReader时,创建此类的实例并将其添加到组合框项集合中。不要忘记设置组合框的DisplayMember和ValueMember

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

答案 1 :(得分:1)

试试这个

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

其中index是您要在组合框中插入的整数值

你的意思是

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

如果您只想添加组合框,请尝试以下

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

我认为您正在寻找 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();
}

答案 2 :(得分:1)

首先,使用Add将项目添加到ComboBox。其次,我希望anonymous type填充ComboBox,同时在您的表单中使用普通原始Sql和简单DataReader

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();
    }

<强>更新

我注意到天真地添加到Item列表不起作用!相反,DataSource的{​​{1}}属性应设置为所需列表。所以工作代码如下:

ComboBox

答案 3 :(得分:0)

Items.Insert正在寻找您在ComboBox列表中的特定点插入。

您想使用Items.Add

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

如果您想使用Insert,则必须是这样的:

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