我使用字典使用绑定源填充我的组合框,但是这会导致列表顶部显示为默认值。
我希望组合框在填充后不显示任何内容,因为当用户选择下拉选项(SelectedIndexChanged)时会触发事件。因此,如果选项可能是他们需要的选项,即使看起来已经被选中,也必须选择它。
字典创建:
public Dictionary<int, string> Get_List_of_SchemesID()
{
Dictionary<int, string> comboSource = new Dictionary<int, string>();
using (SqlConnection cnn = new SqlConnection(connectionString))
{
cnn.Open();
string query = "SELECT [idGMRScheme],[SchemeName] FROM [DBA_Admin].[dbo].[GMR_Schemes]";
using (SqlCommand command = new SqlCommand(query, cnn))
using (SqlDataReader reader = command.ExecuteReader())
while (reader.Read())
{
comboSource.Add((int)reader["idGMRScheme"], (string)reader["SchemeName"]);
}
}
return comboSource;
}
组合人口:
public void Populate_SchemesID_Combolists(Dictionary<int, string> comboSource)
{
cb_Schemes.DataSource = new BindingSource(comboSource, null);
cb_Schemes.ValueMember = "Key";
cb_Schemes.DisplayMember = "Value";
}
答案 0 :(得分:1)
您可以尝试将组合的SelectedIndex设置为-1:
cb_Schemes.SelectedIndex = -1;
答案 1 :(得分:0)
我可以看到两种不同的方法。
首先
更改此方法以向comboBox添加新项目:
public void Populate_SchemesID_Combolists(Dictionary<int, string> comboSource)
{
comboSource.Add(0, ""); //To be the first item displayed
// or
comboSource.Add(0, "Select the Scheme"); // To be default
// maybe you'll need to order by the key asc.
cb_Schemes.DataSource = new BindingSource(comboSource, null);
cb_Schemes.ValueMember = "Key";
cb_Schemes.DisplayMember = "Value";
}
<强>第二强>
public void Populate_SchemesID_Combolists(Dictionary<int, string> comboSource)
{
cb_Schemes.DataSource = new BindingSource(comboSource, null);
cb_Schemes.ValueMember = "Key";
cb_Schemes.DisplayMember = "Value";
cb_Schemes.Text = "";
//or
cb_Schemes.Text = "Select the Scheme";
}
注意:对于这两种方法,在使用comboBox选择项目执行任何操作之前,您需要检查是否选择了正确的项目,如:
if (cb_Schemes.SelectedItem.ToString() != "Select the Scheme" || cb_Schemes.SelectedItem.ToString() != "")
{
//do anything
}
我希望你明白这一点。