C#Winform之comboBox使用注意事项
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/454
要说comboBox,你要用的最多的两个属性应该是DisplayMember和ValueMember。
可今天呢,为了整这个两个属性,弄了好几次发现是“”,想来想去,才发现是SelectedIndex_Changed被触发了,而引发的错误。
举个例子:
using (var myContext = new MyDbContext())
{
var SolutionTable = myContext.MySolutions.Where(x => x.DefenceId == DefenceId1).OrderByDescending(x => x.Rank);
//如果存在解法
if (SolutionTable.Count() != 0)
{
cbxSolution1.DataSource = SolutionTable.ToList();
//初始化Id将触发一次
cbxSolution1.ValueMember = "Id";
//初始化Name将触发一次
cbxSolution1.DisplayMember = "Name";
//初始化SelectedIndex将触发一次,即使你不特意选中0,也会触发SelectedIndex_Changed
cbxSolution1.SelectedIndex = 0;
cbxSolution1.Enabled = true;
//触发一次
cbxSolution1_SelectedIndexChanged(sender, e);
}
}
解决方案:
//先取消一下事件
cbxSolution1.SelectedIndexChanged -= cbxSolution1_SelectedIndexChanged;
//之后再加上去
cbxSolution1.SelectedIndexChanged += cbxSolution1_SelectedIndexChanged;
另外需要提醒的是:
cbxSolution1.DataSource = SolutionTable.ToList();
这里一定要ToList();
因为这里涉及到本地化的事情,在using里面的数据库上下文查询是会被释放掉的,不会保存,ToList()是一个最基本的本地化操作。
参考来源:
[1] Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported.
[2] C# Winform comboBox的常用一些属性和用法
[3] How to add items to Combobox from Entity Framework? - Stack Overflow
[4] C#中comboBox控制他的SelectedIndexChanged事件何时触发问题???在线等待!!!!!
[5] C#调用ComboBox控件的SelectedIndexChanged事件
This article was last edited at 2020-09-08 07:45:11