[C#][Winform]ComboBox的幾個Tips

  • 41090
  • 0
  • C#
  • 2009-09-11

摘要:[C#][Winform]ComboBox的幾個Tips

1.設定ComboBox的值
小小的功能搞了我好幾個小時,值得寫下來紀念。

情境:User從DataGridView選擇某Row,然後把詳細資料顯示在其他的地方以利編輯。

首先先搞定ComboBox,設定好資料來源、顯示和值:

cboxCustomer.DataSource = GetCustomerData();
cboxCustomer.DisplayMember = "Customer_Name";
cboxCustomer.ValueMember = "Customer_ID";

根據User從DataGridView選擇的Row而得來的Customer_Name來設定combobox:

01 internal static void SetDropDownByText(ComboBox cbox, string text)
02
{
03     if (cbox != null)
04
    {
05
06
        //先取得綁定的資料來源
07         DataTable dt = (DataTable)cbox.DataSource;
08
09
        for (int i = 0; i < dt.Rows.Count; i++)
10
        {
11             //開始檢查顯示的文字
12             if ((string)dt.Rows[i][cbox.DisplayMember] == text)
13
            {
14                 cbox.SelectedIndex = i;
15                 break;
16
            }
17
        }
18
    }
19
}

也可利用Customer_Value來設定combobox:

01 internal static void SetDropDownByValue(ComboBox cbox, string text)
02
{
03     if (cbox != null)
04
    {
05        //先取得綁定的資料來源
06         DataTable dt = (DataTable)cbox.DataSource;
07
08
        for (int i = 0; i < dt.Rows.Count; i++)
09
        {
10             //開始檢查給定的值
11             if ((string)dt.Rows[i][cbox.ValueMember] == text)
12
            {
13                 cbox.SelectedIndex = i;
14                 break;
15
            }
16
        }
17
    }
18
}

用法:

SetDropDownByText(cboxCustomer, "Kenny");
SetDropDownByValue(cboxCustomer, "VIP0001");


2.清空ComboBox
如果你的ComboBox有設定DataSource屬性的話(像我上面的範例),那當你用

cboxCustomer.Items.Clear()

這個方法去清空Items時會得到這個錯誤
Items collection cannot be modified when the DataSource property is set.
該怎麼辦呢?


答:清空DataSource即可

cboxCustomer.DataSource = null;

基本上當你使用DataSource這個屬性之後(也就是使用資料來源綁定),想要更動Items(不論是新增還是刪除)都會發生錯誤。如果你要新增或刪除,直接在你的資料來源新增或刪除之後再綁定。
 


3.取得user所選定項目的文字

似乎很難懂,其實想表達的就是類似ComboBox.SelectedText,但是如果你的ComboBox.DropDownStyle屬性設定為DropDownList的話,上述的ComboBox.SelectedText則會回傳空字串。曾經試過許多方法,例如最多人建議的

if (cboxCorp.SelectedItem is string)
    strSelectedText = (string)cboxMembers.SelectedItem;

事實上卻是無效的。試到最後,原來最簡單的最有效:

string strSelectedText = cboxMembers.Text

有時候真的是想太多,也有可能是把web的經驗套用在winform上導致思路被固定住...

 

持續更新中...