1. 程式人生 > >C# WinForm CheckedListBox實現RadioButton的單選且不可取消單選的效果

C# WinForm CheckedListBox實現RadioButton的單選且不可取消單選的效果

//加入ItemCheck方法
this.cblChangeMode.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.SelectOne);

//加入控制是否繼續的全域性變數,防止進入死迴圈
public bool canContinue = true;
private void SelectOne(object sender, ItemCheckEventArgs e)
{
            CheckedListBox clb = sender as CheckedListBox;
            //勾選原選項
            if (clb.CheckedIndices.Count > 0 && clb.CheckedIndices[0] == e.Index && canContinue )
            {
                e.NewValue = CheckState.Checked;
            }
            //第一次勾選
            else if (clb.CheckedIndices.Count == 0)
            {
                canContinue = true;
            }
            //勾選新選項
            else if (clb.CheckedIndices.Count > 0 && clb.CheckedIndices[0] != e.Index)
            {
                canContinue = false;
                clb.SetItemChecked(clb.CheckedIndices[0], false);
            }
            //勾選新選項後重置CanContinue
            else
            {
                canContinue = true;
            }
}

PS:勾選後事件可以寫在CheckedListBox的SelectedIndexChanged事件中,第一次觸發寫在上述程式碼中的“第一次勾選”中。