简体   繁体   English

在C#中的comboBox中初始化一个值

[英]Initialize a value in comboBox in C#

I realize that my comboBox is always empty when program start. 我意识到程序启动时我的comboBox总是空的。 I have to click the arrow beside to choose a value. 我必须单击旁边的箭头选择一个值。 How do we do it so that the comboBox will show a value when the program start? 我们怎么做才能让comboBox在程序启动时显示一个值?

There are the following 4 properties that you can set: 您可以设置以下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

Comment lines straight from MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.aspx 评论直接来自MSDN: http//msdn.microsoft.com/en-us/library/system.windows.forms.combobox.aspx

If you have a combo box and want to set it's Data Source you may do it like this: 如果你有一个组合框并想要设置它的数据源,你可以这样做:

 string[] items = new string[]{"Ram","Shyam"};
    comboBox1.DataSource = items;
    comboBox1.SelectedIndex = 0;

So try to set the SelectedIndex to first index. 因此,尝试将SelectedIndex设置为第一个索引。

试试这段代码:

comboBox1.Items.Add("Test");

Davenewza's answer is great for the programmatic approach (Which I highly recommend). Davenewza的答案非常适合程序化方法(我强烈推荐)。 Another way that is less elegant but utilizes the properties toolbox is to do the following: 另一种不太优雅但利用属性工具箱的方法是执行以下操作:

  1. From the design view, click the comboBox in question. 从设计视图中,单击有问题的组合框。
  2. Navigate to Appearance->Text and enter any string you wish. 导航到Appearance-> Text并输入您想要的任何字符串。

To be safe, I would enter a value that corresponds to something that will be selected in the box to prevent unwanted strings from being propagated to other functions/variables. 为了安全起见,我将输入一个值,该值对应于将在框中选择的内容,以防止不需要的字符串传播到其他函数/变量。 This reason can cause a lot of headaches if not carefully handled, which is why the programmatic approach is preferred. 如果不小心处理,这个原因会引起很多麻烦,这就是为什么程序化方法是首选的原因。

If you are using WPF with MVVM and INotifyPropertiesChanged interface, then you can set a fallback value in your binding property. 如果您将WPF与MVVM和INotifyPropertiesChanged接口一起使用,则可以在绑定属性中设置回退值。 SelectedIndex="{Binding SelectedCountry.MultipleClassCountry, FallbackValue= 0}" Setting SelectedIndex = 0 should select the first Item you have in your combobox. SelectedIndex="{Binding SelectedCountry.MultipleClassCountry, FallbackValue= 0}"设置SelectedIndex = 0应选择组合框中的第一个项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM