由于工作需要,需要实现复选框的单选与多选功能,找了好多资料都不是很全,经过两天苦苦的挖挖挖,终于完成啦O(∩_∩)O哈哈~
用DEV控件中的CheckedListBoxControl控件,当然VS中的复选框组合控件应该按照下面方法也可以实现该功能,可以试下(⊙o⊙)哦
代码来啦O(∩_∩)O哈哈~
1 //首先触发SelectedIndexChanged事件,然后再触发ItemCheck事件 2 3 //存储选中的复选框的值 4 string strGXY=string.Empty; 5 private void chkGXYGrade_SelectedIndexChanged(object sender, EventArgs e) 6 { 7 8 //先把所有的选择框的状态都置为不选中的状态 9 for (int i = 0; i < chkGXYGrade.Items.Count; i++)10 {11 chkGXYGrade.SetItemCheckState(i, CheckState.Unchecked);12 }13 }14 15 private void chkGXYGrade_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)16 {17 //如果复选框选中的数目大于0,把选中的复选框的索引和e.Index(获取的当前选中点击的复选框的索引)比较,如果相等就把该复选框选中,否则置为非选中状态18 if (chkGXYGrade.CheckedItems.Count > 0)19 {20 for (int i = 0; i < chkGXYGrade.Items.Count; i++)21 {22 if (i != e.Index)23 {24 chkGXYGrade.SetItemCheckState(i, CheckState.Unchecked);25 }26 }27 }28 else29 {30 31 //如果复选框选中的数据小于0 ,则把所有的复选框的状态都置为未选中的状态32 for (int i = 0; i < chkGXYGrade.Items.Count; i++)33 {34 35 chkGXYGrade.SetItemCheckState(i, CheckState.Unchecked);36 strGXY = string.Empty;37 }38 39 }40 41 42 //循环复选框,根据选中的状态来获取选中的复选框的值43 for (int i = 0; i < chkGXYGrade.Items.Count; i++)44 {45 if (chkGXYGrade.Items[i].CheckState == CheckState.Checked)46 {47 strGXY = chkGXYGrade.GetItemText(i).ToString();48 }49 }50 }
1 //记录复选框选中的状态 2 CheckState csGXB; 3 4 //存储复选框选中的值(多选以‘/’区分 ) 5 string strGXB = string.Empty; 6 7 //先触发SelectedIndexChanged事件,再触发ItemCheck事件 8 private void chbGXBlb_SelectedIndexChanged(object sender, EventArgs e) 9 {10 switch (csGXB)11 {12 case CheckState.Checked:13 14 strGXB = string.Empty;15 for (int i = 0; i < chbGXBlb.Items.Count; i++)16 {17 //获取选中的复选框的值18 if (chbGXBlb.GetItemChecked(i))19 {20 if (strGXB == string.Empty)21 {22 strGXB = chbGXBlb.GetItemText(i);23 }24 else25 {26 strGXB += "/" + chbGXBlb.GetItemText(i);27 }28 }29 }30 break;31 case CheckState.Unchecked:32 strGXB = string.Empty;33 for (int i = 0; i < chbGXBlb.Items.Count; i++)34 {35 if (chbGXBlb.GetItemChecked(i))36 {37 if (strGXB == string.Empty)38 {39 strGXB = chbGXBlb.GetItemText(i);40 }41 else42 {43 strGXB = strGXB + "/" + chbGXBlb.GetItemText(i);44 }45 }46 }47 break;48 49 }50 51 }52 53 54 private void chbGXBlb_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)55 {56 // e.State,获取当前复选框的选中还是未选中的状态(Checked 或UnChecked)57 csGXB = e.State;58 chbGXBlb_SelectedIndexChanged(null, null);59 }