简体   繁体   English

无法在组合框中设置默认值:C#

[英]not able to set default value in combobox : C#

I was trying to add a default value ("--select item--") in existing ComboBox which is getting filled by Database table. 我试图在数据库表中填充的现有ComboBox中添加默认值(“ --select item--”)。 Here is my code. 这是我的代码。

SqlConnection conn = new SqlConnection("Server = .\\SQLEXPRESS; Initial Catalog= Student; Trusted_Connection = True");
string query = "select Id, Name from abc1";
SqlDataAdapter da = new SqlDataAdapter();
conn.Open();
DataTable dt = new DataTable();

SqlCommand command = new SqlCommand(query, conn);

SqlDataReader reader = command.ExecuteReader();

dt.Load(reader);

comboBox1.DataSource = dt;
comboBox1.ValueMember = "Id";
comboBox1.DisplayMember = "Name";      

Everything is working fine in above code and I'm getting CB filled with desired values. 在上面的代码中,一切工作正常,并且CB中填充了所需的值。

Now when I try to insert default value using below, then it is throwing an error. 现在,当我尝试使用下面的内容插入默认值时,则会引发错误。 This way was tried here 这种方式在这里尝试过

comboBox1.Items.Insert(0, "Select"); //this is throwing an error
comboBox1.SelectedIndex = 0;

在此处输入图片说明

I further explored below code to add default item. 我进一步探索了以下代码以添加默认项。

comboBox1.SelectedIndex = -1;
comboBox1.Text = "Select an item";

This added an item as desired, but on any event, CB loses this value. 这根据需要添加了一个项目,但是无论如何,CB都会丢失此值。 After SelectIndexChanged event, I lose this value. SelectIndexChanged事件之后,我丢失了该值。 So this cannot be my solution. 所以这不是我的解决方案。

Any advise? 有什么建议吗?

I'd rather not intefere into binding, but edit SQL instead: 我宁愿不干预绑定,而是编辑 SQL:

string query = 
  @"select 0 as Id,        -- or whatever default value you want
           'select' as Name, 
           0, 
     union all
    -- your original query here
    select Id, 
           Name,
           1  
      from abc1
    -- to have default value on the top
  order by 3 asc";

Insert's second parameter is expecting a ComboBox.ObjectCollection object. 插入的第二个参数需要一个ComboBox.ObjectCollection对象。 Try doing this: 尝试这样做:

Having a class 上课

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }
}

And using: 并使用:

// This could be inline, but for simplicity step by step...
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;

comboBox1.Items.Add(item);
//or
comboBox1.Items.Insert(0, item);

You can add programmatically the item to the datatable 您可以通过编程方式将该项目添加到数据表中

DataRow dr = dt.NewRow();
dr["id"] = "0";
dr["name"] = "Select";

dt.Rows.InsertAt(dr, 0);

then you can set the datasource 然后您可以设置数据源

comboBox1.DataSource = dt;

If you just want to show a suggestion text to your user, the "EDIT" part of this answer may help (can only work if your ComboBox 's DropDownStyle is not set to DropDownList ). 如果您只想向用户显示建议文本,则此答案的“编辑”部分可能会有所帮助(仅在ComboBoxDropDownStyle未设置为DropDownList )。

But if you really want some "Select" item in your ComboBox , try this: 但是,如果您确实想要在ComboBox一些“选择”项,请尝试以下操作:

    void Form1_Load(object sender, EventArgs e)
    {
        //load your datatable here
        comboBox1.ValueMember = "ID";
        comboBox1.DisplayMember = "Name";
        comboBox1.Items.Add(new { ID = 0, Name = "Select" });
        foreach (DataRow a in dt.Rows)
            comboBox1.Items.Add(new { ID = a["ID"], Name = a["Name"] });
        comboBox1.SelectedIndex = 0;
        comboBox1.DropDown += new EventHandler(comboBox1_DropDown);
        comboBox1.DropDownClosed += new EventHandler(comboBox1_DropDownClosed);
    }

    void comboBox1_DropDownClosed(object sender, EventArgs e)
    {
        if (!comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
        {
            comboBox1.Items.Insert(0, new { ID = 0, Name = "Select" });
            comboBox1.SelectedIndex = 0;
        }
    }

    void comboBox1_DropDown(object sender, EventArgs e)
    {
        if (comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
            comboBox1.Items.Remove(new { ID = 0, Name = "Select" });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM