【发布时间】: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 事件之后,我失去了这个价值。所以这不能是我的解决方案。
有什么建议吗?
【问题讨论】:
-
这应该会有所帮助:stackoverflow.com/a/5134229/2572551