2010-02-12 79 views
2

我嘗試設置這樣的:如何在winform c#中設置列表框的默認選定項?

ListBox lb = new ListBox();
/* Bind datas */
lb.SelectedItem = someObject;

磅忠實地選擇了someObject項目。但它會首先選擇第一項。那個動作會導致我不想要的SelectedIndexChanged事件。

我只想在選擇someObject時調用SelectedIndexChanged。 我該如何解決這個問題?

回答

4

當您不希望它觸發時,在窗體/控件上使用標誌來禁用事件。

public class Form1 : Form 
{ 
    private bool itemsLoading; 

    public Form1() 
    { 
     InitializeComponent(); 
     LoadListItems(); 
    } 

    private void LoadListItems() 
    { 
     itemsLoading = true; 
     try 
     { 
      listBox1.DataSource = ... 
      listBox1.SelectedItem = ... 
     } 
     finally 
     { 
      itemsLoading = false; 
     } 
    } 

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     if (itemsLoading) 
      return; 

     // Handle the changed event here... 
    } 
} 
+0

這是很酷的解決方案! 謝謝! – Jennal 2010-02-13 01:03:09

1

直到您將selectedItem更改爲someObject之後才添加selectedIndexChanged事件?

將事件從表單編輯器或者designer.cs中移出,然後使用自動生成的相同代碼手動添加它?

相關問題