2017-03-16 43 views
0

我在Windows窗體應用程序中創建Combobox我希望在第0個索引值「選擇」我該怎麼做?我試過在Windows窗體Combobox默認值

cbxWeigtType Item = new cbxWeigtType(); 
Item.Text = "my string"; 
this.DropDownList1.SelectedItem = Item; 
+0

是否要選擇第一項的值或將默認選擇的組合框設置爲第一項? – ReadyFreddy

+0

先生我想設置默認選擇 –

回答

2

你可以這樣做:在第0指數

comboBox1.Items.Insert(0, "Select"); 
comboBox1.SelectedIndex = 0; 

插入,然後將其設置爲selectedIndex

+1

謝謝先生它正常工作 –

+0

先生它的工作當combobox是空的,但如果combox綁定與數據源然後它不工作,因爲我想添加「選擇」在第0索引而combobox與數據綁定來源 –

+0

先生它顯示以下錯誤({「設置數據源屬性時不能修改項目集合。」)) –

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"; 
}