[英]Initialize a value in comboBox in C#
我意識到程序啟動時我的comboBox總是空的。 我必須單擊旁邊的箭頭選擇一個值。 我們怎么做才能讓comboBox在程序啟動時顯示一個值?
您可以設置以下4個屬性:
// Gets or sets the index specifying the currently selected item.
comboBox1.SelectedIndex = someIndex; //int
// Gets or sets currently selected item in the ComboBox.
comboBox1.SelectedItem = someItem; // object
// Gets or sets the text that is selected in the editable portion of a ComboBox.
comboBox1.SelectedText = someItemText; // string
// Gets or sets the value of the member property specified by the ValueMember property.
comboBox1.SelectedValue = someValue; // object
評論直接來自MSDN: http : //msdn.microsoft.com/en-us/library/system.windows.forms.combobox.aspx
如果你有一個組合框並想要設置它的數據源,你可以這樣做:
string[] items = new string[]{"Ram","Shyam"};
comboBox1.DataSource = items;
comboBox1.SelectedIndex = 0;
因此,嘗試將SelectedIndex
設置為第一個索引。
試試這段代碼:
comboBox1.Items.Add("Test");
Davenewza的答案非常適合程序化方法(我強烈推薦)。 另一種不太優雅但利用屬性工具箱的方法是執行以下操作:
為了安全起見,我將輸入一個值,該值對應於將在框中選擇的內容,以防止不需要的字符串傳播到其他函數/變量。 如果不小心處理,這個原因會引起很多麻煩,這就是為什么程序化方法是首選的原因。
如果您將WPF與MVVM和INotifyPropertiesChanged
接口一起使用,則可以在綁定屬性中設置回退值。 SelectedIndex="{Binding SelectedCountry.MultipleClassCountry, FallbackValue= 0}"
設置SelectedIndex = 0
應選擇組合框中的第一個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.