【问题标题】:not able to set default value in combobox : C#无法在组合框中设置默认值:C#
【发布时间】:2023-03-11 05:50:01
【问题描述】:

我试图在由数据库表填充的现有 ComboBox 中添加默认值(“--select item--”)。这是我的代码。

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";      

在上面的代码中一切正常,我让 CB 充满了所需的值。

现在,当我尝试使用下面插入默认值时,它会引发错误。这条路是tried here

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

我进一步explored下面的代码添加默认项目。

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

这根据需要添加了一个项目,但在任何情况下,CB 都会失去这个值。在SelectIndexChanged 事件之后,我失去了这个价值。所以这不能是我的解决方案。

有什么建议吗?

【问题讨论】:

标签: c# winforms combobox


【解决方案1】:

我宁愿不干扰绑定,而是编辑 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";

【讨论】:

  • 这是一个棘手的解决方案..我想到了,但让我在 c# 方面探索解决方案..
【解决方案2】:

插入的第二个参数需要一个ComboBox.ObjectCollection 对象。 尝试这样做:

上课

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

并使用:

// 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);

【讨论】:

  • 不,没有错误。执行成功。但是没有得到想要的项目... CB 显示的只是数据库中的值..
【解决方案3】:

您可以通过编程方式将项目添加到数据表中

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

dt.Rows.InsertAt(dr, 0);

然后你可以设置数据源

comboBox1.DataSource = dt;

【讨论】:

    【解决方案4】:

    如果您只想向您的用户显示建议文本,this answer 的“编辑”部分可能会有所帮助(仅当您的ComboBoxDropDownStyle 未设置为DropDownList 时才有效)。

    但如果你真的想在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" });
        }
    

    【讨论】:

    • 这不是很长吗?
    • 是的,如果您不介意在下拉列表中显示“选择”项,只需将 comboBox1.DataSource = dt; 替换为 comboBox1.Items.Add(new { ID = 0, Name = "Select" }); foreach (DataRow a in dt.Rows) comboBox1.Items.Add(new { ID = a["ID"], Name = a["Name"] });
    • 或者在将 ComboBox 的 DataSource 设置为 @user3401335 建议之前,在数据表顶部添加一个新行。
    猜你喜欢
    • 2014-02-14
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2017-10-03
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多