1.在界面中添加一个combox
2.将数据绑定到combox
List<GrindingType> type = new List<GrindingType>();
type.Add(new GrindingType { Id = 1, Name = "Product A", Type = new List<string> { "1", "2" } });
type.Add(new GrindingType { Id = 2, Name = "Product 2", Type = new List<string> { "1", "2" } });
type.Add(new GrindingType { Id = 3, Name = "Product 3", Type = new List<string> { "1", "2" } });
type.Add(new GrindingType { Id = 4, Name = "自定义",Type=null});
comboBox1.DataSource = type; // 使用DataSource属性加载数据,
comboBox1.DisplayMember = "Name"; // 设置显示成员为Name属性。
comboBox1.ValueMember = "Id"; // 设置值成员为Id属性。
3.为combox添加列表变动事件
4.获取列表点击列数据
//获取comboBox的DisplayMember值
Console.WriteLine("DisplayMember:" + comboBox1.Text);
//获取comboBox的ValueMember值
Console.WriteLine("ValueMember:" + comboBox1.SelectedValue.ToString());
//获取combox上绑定数据
GrindingType grindingType = (GrindingType)comboBox1.SelectedItem;
Console.WriteLine("选中值:" + grindingType.Id + "..." + grindingType.Name);
5.完整实现
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public class GrindingType
{
public int Id { get; set; }
public string Name { get; set; }
public List<string> Type { get; set; }
}
public Form1()
{
InitializeComponent();
LoadComboBoxData();
}
private void LoadComboBoxData()
{
List<GrindingType> type = new List<GrindingType>();
type.Add(new GrindingType { Id = 1, Name = "Product A", Type = new List<string> { "1", "2" } });
type.Add(new GrindingType { Id = 2, Name = "Product 2", Type = new List<string> { "1", "2" } });
type.Add(new GrindingType { Id = 3, Name = "Product 3", Type = new List<string> { "1", "2" } });
type.Add(new GrindingType { Id = 4, Name = "自定义", Type = null });
comboBox1.DataSource = type; // 使用DataSource属性加载数据,
comboBox1.DisplayMember = "Name"; // 设置显示成员为Name属性。
comboBox1.ValueMember = "Id"; // 设置值成员为Id属性。
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
Console.WriteLine("===================SelectedValueChanged=======================");
//获取comboBox的DisplayMember值
Console.WriteLine("DisplayMember:" + comboBox1.Text);
//获取comboBox的ValueMember值
Console.WriteLine("ValueMember:" + comboBox1.SelectedValue.ToString());
//获取combox上绑定数据
GrindingType grindingType = (GrindingType)comboBox1.SelectedItem;
Console.WriteLine("选中值:" + grindingType.Id + "..." + grindingType.Name);
}
}
}