[英]Winforms checkedlistbox check one item
我的表單上有一個CheckedListBox
控件,我希望用戶只能在此列表中一次檢查一個項目(因此我有效地想要一些模仿“RadioListBox”的東西)。
這可能與CheckedListBox
還是我必須通過其他方式即興創作?
如果重要,則通過從數據庫加載項來填充表單加載中的CheckedListBox
。
謝謝
編輯
我想我應該澄清一下,我不打算限制用戶可以選擇的數量(即SelectionMode屬性),而不是他們可以檢查多少。
您可以通過在CheckedListBox上為ItemCheck添加事件檢查來實現,並使用如下函數:
private static bool checkIfAllowed(CheckedListBox listBox) {
if (listBox.CheckedItems.Count > 0) {
return false;
}
return true;
}
那么在你想要的情況下:
if (checkIfAllowed) {
...
} else {
}
此外,您可以通過添加另一個功能/方法來改進這一點,該功能/方法將在允許檢查項目之前取消選中所有項目。 因此,當用戶單擊某個復選框時,將取消選中所有其他復選框。
要取消選中所有選中的項目,只需使用:
private static void uncheckAll(CheckedListBox listBox) {
IEnumerator myEnumerator;
myEnumerator = listBox.CheckedIndices.GetEnumerator();
int y;
while (myEnumerator.MoveNext() != false) {
y = (int)myEnumerator.Current;
listBox.SetItemChecked(y, false);
}
}
因此,在ItemCheck事件中,您必須先運行uncheckAll(yourListBox)
,然后只需檢查該項。
編輯:我已經使用以下代碼測試它,它的工作原理。 沒有if它拋出異常。
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
if (e.NewValue == CheckState.Checked) {
IEnumerator myEnumerator;
myEnumerator = checkedListBox1.CheckedIndices.GetEnumerator();
int y;
while (myEnumerator.MoveNext() != false) {
y = (int)myEnumerator.Current;
checkedListBox1.SetItemChecked(y, false);
}
}
}
這段代碼可以簡單得多,需要一個變量。 每次你檢查一個新的盒子時,它都會取消選中最后一個盒子,導致當時沒有兩個被檢查的項目或更多。 確保屬性SelectionMode = SelectionMode.One;
如上所述設置。
private int lastCheck = -1;
private void CheckListBox_IndexChanged(object sender, EventArgs e) {
int toUncheck = lastCheck;
if (toUncheck != -1)
CheckListBox.SetItemChecked(toUncheck, false);
lastCheck = CheckListBox.SelectedIndex;
CheckListBox.SetItemChecked(lastCheck, true);
}
或者,如果需要,您可以將lastCheck設置為默認復選框,通過以下方式執行此操作:
private void FormFoo_Load(object sender, EventArgs e) {
CheckListBox.SelectedIndex = 0;
lastCheck = CheckListBox.SelectedIndex;
}
然后我在上面提到的其余代碼如下。
注意*:我使用了lastCheck = **CheckListBox.SelectedIndex;**
來支持鍵盤移動,以防萬一。
我必須做類似的事情從大量列表中選擇一個用戶。 沒有RadioListBox可以說,所以我只是手動編碼...
對不起,在VB中,我只是粘貼它,邏輯是一樣的。
Private m_NoFire As Boolean = False
Private Sub lstSource_ItemCheck( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles lstSource.ItemCheck
'When the checked state is set programatically,
'this event will still fire and cause the loop
'to run - infinatly. This line prevents that.
If m_NoFire Then Exit Sub
m_NoFire = True
'Ensure only one item is selected
For i As Integer = 0 To lstSource.Items.Count - 1
If Not lstSource.SelectedIndex = i Then
lstSource.SetItemChecked(i, False)
End If
Next
m_NoFire = False
End Sub '-- lstSource_ItemCheck
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.