最近寫Winform程式,發現Winform中的ComboBox和Web中的Dropdown相差很大,在ComboBox 绑定数据源 會触发SelectedIndexChanged事件,很困擾,查找了資料,處理方法大體分為三種
1.添加一个标记位,在绑定前设置为false,绑定完成后设置回true(個人覺得用起來的很奇怪)
void BindComboBox() { flag=false; ComboxBox1.ValueMember="ValueColumn"; ComboxBox1.DisplayMember="DisplayColumn"; ComboxBox1.DataSource=DataTable1; flag=true; } privatevoid ComboxBox1_SelectedIndexChanged(object sender, EventArgs e) { if(flag) { //Do something } }
2.绑定前,将SelectedIndexChanged的委托去掉,等绑定完成后,再添加事件委托(覺得比較複雜)
void BindComboBox() { //去除委托 ComboBox1.SelectedIndexChanged -= new EventHandler(ComboBox1_SelectedIndexChanged); ComboBox1.DataSource = null; ComboBox1.ValueMember = "ValueColumn"; ComboBox1.DataSource = DataTable1; //添加委托 ComboBox1.SelectedIndexChanged += new EventHandler(ComboBox1_SelectedIndexChanged); ComboBox1.DisplayMember = "DisplayColumn"; }
3.判斷是否是選擇狀態(最後本人用的)
privatevoid ComboxBox1_SelectedIndexChanged(object sender, EventArgs e) { if(ComboxBox1.ContainsFocus) { //Do something } }
原文地址:https://www.cnblogs.com/superfeeling/p/12392959.html
时间: 2024-11-10 20:10:33