winform ComboBox 代码使用
时间: 2024-06-16 21:08:05 浏览: 187
WinForm ComboBox是一种常用的控件,用于在Windows Form应用程序中选择或输入文本值。下面是使用WinForm ComboBox的代码示例:
首先,在窗体设计器中添加一个ComboBox控件,并设置其属性,例如:
```csharp
private System.Windows.Forms.ComboBox comboBox1;
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"Item1",
"Item2",
"Item3"});
this.comboBox1.Location = new System.Drawing.Point(12, 12);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 21);
this.comboBox1.TabIndex = 0;
```
然后,在代码中可以使用以下方法对ComboBox进行操作:
1. 绑定数据源:使用DataSource属性将ComboBox绑定到数据源,例如:
```csharp
this.comboBox1.DataSource = myDataTable;
this.comboBox1.DisplayMember = "displayMember";
this.comboBox1.ValueMember = "valueMember";
```
2. 添加项:使用Items属性添加项,例如:
```csharp
this.comboBox1.Items.Add("NewItem");
```
3. 选择项:使用SelectedIndex属性或SelectedItem属性选择项,例如:
```csharp
this.comboBox1.SelectedIndex = 0;
// or
this.comboBox1.SelectedItem = "Item2";
```
4. 获取选中项:使用SelectedValue属性或SelectedIndex属性获取选中项的值或索引,例如:
```csharp
string selectedValue = this.comboBox1.SelectedValue.ToString();
int selectedIndex = this.comboBox1.SelectedIndex;
```
5. 处理选择项改变事件:使用SelectedIndexChanged事件处理选择项改变事件,例如:
```csharp
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = this.comboBox1.SelectedValue.ToString();
// do something with selectedValue
}
```
阅读全文