组合框填充数据表后缺少第一个组合框项目

时间:2014-11-13 10:20:36

标签: c# winforms combobox datatable

我的表单上有comboboxdatatablecombobox将填充datatable的某些行值。但在此之前,我想添加一个名为(new)combobox项,如果用户想添加新项目,它将成为combobox的第一个选项

但是当我的combobox被填满时,我的(新)因某些原因不会出现。

string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);
comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
    comboSMSMessages.Items.Clear();

    for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
    {
        ComboboxItem item = new ComboboxItem()
        {
            Text = dtSmsMessages.Rows[i]["Name"].ToString(),
            Value = dtSmsMessages.Rows[i]["Id"].ToString()
        };
        comboSMSMessages.Items.Add(item);
    }
}
comboSMSMessages.SelectedIndex = 0;

1 个答案:

答案 0 :(得分:2)

comboSMSMessages.Items.Clear();清除所有项目      添加comboSMSMessages.Items.Add(new ComboboxItem(){Text =“(new)”,Value =“ - 1”});      清除组合框后,您的代码应该像

string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);

if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
comboSMSMessages.Items.Clear();

comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
{
 ComboboxItem item = new ComboboxItem()
    {
        Text = dtSmsMessages.Rows[i]["Name"].ToString(),
        Value = dtSmsMessages.Rows[i]["Id"].ToString()
    };
    comboSMSMessages.Items.Add(item);
 }
}
comboSMSMessages.SelectedIndex = -1;