在C#中初始化组合框中的一个值#

问题描述:

我意识到程序启动时我的comboBox总是空的。我必须点击旁边的箭头才能选择一个值。我们该怎么做,以便程序启动时comboBox会显示一个值?在C#中初始化组合框中的一个值#

+1

Winform WPF aspnet? – V4Vendetta 2012-07-24 10:43:34

试试这个代码:

comboBox1.Items.Add("Test"); 
+0

你们能解除对我的禁令吗?再给我一次机会。 – maniac84 2012-08-03 09:14:49

有,你可以设置以下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设置为第一个索引。

Davenewza的答案非常适合程序化方法(我强烈推荐)。另一种不太优雅但利用属性工具箱的方法是执行以下操作:

  1. 从设计视图中,单击相关组合框。
  2. 导航到外观 - >文本并输入您希望的任何字符串。

为了安全起见,我会输入一个值,该值对应于在框中选择的内容,以防止不需要的字符串传播到其他函数/变量。如果不仔细处理,这个原因会导致很多头痛,这就是为什么程序化方法更受欢迎的原因。