2010-03-13 54 views
4

有沒有辦法讓ListBox中的某些項目只讀/禁用,因此無法選擇它們?或者是否有任何類似ListBox的控件來提供這種功能?有隻讀/禁用項目的WinForms列表框

+0

此鏈接可以幫助禁用checkedListBox中的項目使用C#Winform http://www.dotnettechy.com/problem-solutions/disabling-an-item-in-a-checkedlistbox-c-winform-10.aspx – 2012-01-31 15:08:16

回答

3

ListBox不支持。你可以栓上一些東西,你可以取消選擇一個選定的項目。下面是防止偶數項被選中一個愚蠢的例子:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { 
    for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; ix--) { 
    if (listBox1.SelectedIndices[ix] % 2 != 0) 
     listBox1.SelectedIndices.Remove(listBox1.SelectedIndices[ix]); 
    } 
} 

但閃爍是相當明顯,它打亂了鍵盤導航。您可以通過使用CheckedListBox獲得更好的效果,可以防止用戶檢查框的項目:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { 
    if (e.Index % 2 != 0) e.NewValue = CheckState.Unchecked; 
} 

但是現在你不能覆蓋圖紙,使它看起來明顯的是,該項目是不可選的用戶。這裏沒有很好的解決方案,只是不在盒子中顯示不應該選擇的項目就簡單多了。

1

@Hans解決方案導致短時間選擇物品ID,然後選擇消失。我不喜歡這樣 - 這可能會讓最終用戶感到困惑。

我寧願隱藏應禁用該項目的一些編輯選項按鈕:

 if (lbSystemUsers.Items.Count > 0 && lbSystemUsers.SelectedIndices.Count > 0) 
      if (((RemoteSystemUserListEntity)lbSystemUsers.SelectedItem).Value == appLogin) 
      { 
       bSystemUsersDelete.Visible = false; 
       bSystemUsersEdit.Visible = false;      
      } 
      else 
      { 
       bSystemUsersDelete.Visible = true; 
       bSystemUsersEdit.Visible = true; 
      } 

這裏列出了用戶和禁止以編輯到編輯面板實際登錄的用戶列表。

1

ListBox沒有ReadOnly(或類似)屬性,但可以自定義ListBox控件。下面是一個工作非常適合我的解決方案:

https://ajeethtechnotes.blogspot.com/2009/02/readonly-listbox.html

public class ReadOnlyListBox : ListBox 
{ 
    private bool _readOnly = false; 
    public bool ReadOnly 
    { 
     get { return _readOnly; } 
     set { _readOnly = value; } 
    } 

    protected override void DefWndProc(ref Message m) 
    { 
     // If ReadOnly is set to true, then block any messages 
     // to the selection area from the mouse or keyboard. 
     // Let all other messages pass through to the 
     // Windows default implementation of DefWndProc. 
     if (!_readOnly || ((m.Msg <= 0x0200 || m.Msg >= 0x020E) 
      && (m.Msg <= 0x0100 || m.Msg >= 0x0109) 
      && m.Msg != 0x2111 
      && m.Msg != 0x87)) 
     { 
      base.DefWndProc(ref m); 
     } 
    } 
} 
0

我知道這是舊線,但我會後對未來的其他讀者一種解決方法。

listBox.Enabled = false; 
listBox.BackColor = Color.LightGray; 

這會將列表框的背景顏色更改爲淺灰色。所以這不是內置的「本地方式」,但至少給了用戶一些反饋,他不應該/不能編輯該字段。