2017-04-12 67 views
0

我綁定了一個ComboBox與數據源它顯示下拉菜單中的數據源,但我想要一個默認選定的值。DropDown當DropDown在Windows窗體應用程序中的默認選定值綁定數據源

實施例:
「選擇」 默認情況下選擇像顯示在此picture

在我的情況的結果是顯示像this

這是我的代碼:

public void BindComboBoxItem() 
{ 
    try 
    { 
     ItemRepository repo = new ItemRepository(); 
     List<Item> items = repo.GetAll(); 
     cbxSelectItem.DataSource = items; 
     cbxSelectItem.DisplayMember = "Name"; 
     cbxSelectItem.ValueMember = "Id"; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(MessageResource.ErrorMessage, "Error", 
        MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
} 
+0

你總是希望選擇一個值還是應該讓用戶能夠選擇一個空的域?/清除它 – EpicKip

+1

這個答案對你有幫助嗎? - http://stackoverflow.com/a/8064216/5598843 –

+0

我在ComboBox中設置了一些項目,並且其中沒有選擇它們。我想在這種情況下顯示組合「請選擇項目」的字符串。 –

回答

0

如果你想擁有「選擇」作爲默認選擇的值,那麼你需要添加它您的項目,並設置

cbxSelectItem.SelectedIndex = //input the index of "Select" 

這是你的第一個圖像鏈接的情況下0

+0

這隻有在你知道索引時纔有效。他的數據綁定組合框,所以這可能會改變 – EpicKip

+0

需要注意的一點很好。感謝您指出@EpicKip –

0

通過設置DropDownStyle,組合框始終有一個選定的值。如果你不想要這種行爲,你只能使用最後一行。

//This makes it so you have to select a value from the list, there is also 1 auto selected 
comboBox.DropDownStyle = ComboBoxStyle.DropDownList; 
//This makes sure we're selecting the value we want 
comboBox.SelectedIndex = comboBox.Items.IndexOf("value"); 

如果你想添加的項目告訴人們選擇一個值,你可以這樣做:

comboBox.Items.Insert(0, "Please select any value"); 

注*這將創建一個可選項目,如果你不希望這樣你可以這樣做:

private void comboBox_TextChanged(object sender, EventArgs e) 
{ 
    if(comboBox.SelectedIndex <= 0) 
    { 
     comboBox.Text = "Please select a value"; 
    } 
} 

private void Form_Load(object sender, EventArgs e) 
{ 
    comboBox.Text = "Please select a value"; 
} 
0

它可以使用密鑰對我的代碼做的是這裏

private void BindComboBoxItem() 
    { 
     ItemRepository repo = new ItemRepository(); 
     List<Item> items = repo.GetAll(); 
     List<KeyValuePair<int, string>> allitems = new List<KeyValuePair<int, string>>(); 
     KeyValuePair<int, string> first = new KeyValuePair<int, string>(0, "Please Select"); 
     allitems.Add(first); 
     foreach (Item item in items) 
     { 
      KeyValuePair<int, string> obj = new KeyValuePair<int, string>(item.Id, item.Name); 
      allitems.Add(obj); 
     } 
     cbxSelectItem.DataSource = allitems; 
     cbxSelectItem.DisplayMember = "Value"; 
     cbxSelectItem.ValueMember = "Key"; 
    } 
相關問題