c# - 如何修复“组合框选定索引始终显示第一个值 C#”
问题描述
我有一个 Windows 窗体应用程序,它在加载时会用来自 mysql 的数据填充我的组合框。但是在加载时,我需要先有一个空值,而不是从组合框中选择第一个。
我试过了combobox.SelectedIndex = -1
;它可以工作,但我使用消息提示进行调试,我可以看到该消息显示组合框中的第一个值,然后再显示无。
void Fillcombo()
{
DataTable tb = new DataTable("candidate_l");
connection.Open();
string QueryPres = "SELECT candidate_nu, CONCAT(candidate_n, ' ' ,candidate_s) AS fullname FROM candidate_l WHERE candidate_p = 'PRES'";
cmd = new MySqlCommand(QueryPres, connection);
mdr = cmd.ExecuteReader();
tb.Load(mdr);
cbo_President.ValueMember = "candidate_nu";
cbo_President.DisplayMember = "fullname";
cbo_President.DataSource = tb;
cbo_President.SelectedIndex = -1;
cbo_President.Text = "No Selection";
connection.Close();
}
private void cbo_President_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbo_President.SelectedIndex > -1)
{
string cbopres = cbo_President.SelectedValue.ToString();
MessageBox.Show("Candidate ID : " + cbopres);
}
else if (cbo_President.SelectedIndex == -1)
{
MessageBox.Show("Candidate ID : none");
}
}
我需要Candidate ID : none
在 else if 语句中得到消息。因为我一直在获得Candidate ID
组合框中的第一项。
解决方案
解决此问题的常见模式是在设置/初始化控件时删除事件处理程序并在初始化后添加事件处理程序。
comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
comboBox1.DataSource = test;
comboBox1.SelectedIndex = -1;
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
推荐阅读
- python - 将 Python Pandas Groupby() 行与另一个 Groupby() 值相加?
- javascript - 添加 AOS JS 库后,我的自定义 CSS 过渡动画无法悬停
- java - 如何从 Firebase 授权中检索信息
- swift - 可可(macOS)中 AVAudioRecorder 的正确用法是什么?
- c++ - 使用 C++ gRPC 生成的存根文件(.pb.h/cc、grpc.pb.h/cc)构建控制台应用程序时,链接错误 (LNK2001) 无法解析外部符号
- python - 在 Python 中查找行值并替换列名
- oracle - 如何在 Oracle 中将 Unix 时间戳转换为本地日期?
- mysql - 将列设置为索引
- javascript - React JS-TypeError:products.map 不是函数
- windows - 这意味着什么以及如何扭转它?