c#中怎么像COMBOX中添加值和名称。最好举个例子
3个回答
展开全部
需知comboBox里的项都是对象实例
新建一个类
/// <summary>
/// 选择项类,用于ComboBox或者ListBox添加项
/// </summary>
public class ListItem:System.Object
{
private string id = string.Empty;
public string Id
{
get { return id; }
set { id = value; }
}
private string name = string.Empty;
public string Name
{
get { return name; }
set { name = value; }
}
public ListItem(string sid, string sname)
{
this.Id = sid;
this.Name = sname;
}
public override string ToString()
{
return this.Name;
}
}
static void Main()
{
List<ListItem> items = new List<ListItem>();//添加项的集合
ListItem item = new ListItem("显示文字内容1","value值1");
ListItem item = new ListItem("显示文字内容2","value值2");
ListItem item = new ListItem("显示文字内容3","value值3");
items.Add(item);
comboBoxGroup.DisplayMember = "Name";
comboBoxGroup.ValueMember = "Id";
comboBoxGroup.DataSource = items;
this.comboBoxGroup.SelectedIndex = 0;
//下拉框事件
comboBoxGroup.SelectedIndexChanged += new EventHandler(comboBoxGroup_SelectedIndexChanged);
return 0;
}
搞定~
}
新建一个类
/// <summary>
/// 选择项类,用于ComboBox或者ListBox添加项
/// </summary>
public class ListItem:System.Object
{
private string id = string.Empty;
public string Id
{
get { return id; }
set { id = value; }
}
private string name = string.Empty;
public string Name
{
get { return name; }
set { name = value; }
}
public ListItem(string sid, string sname)
{
this.Id = sid;
this.Name = sname;
}
public override string ToString()
{
return this.Name;
}
}
static void Main()
{
List<ListItem> items = new List<ListItem>();//添加项的集合
ListItem item = new ListItem("显示文字内容1","value值1");
ListItem item = new ListItem("显示文字内容2","value值2");
ListItem item = new ListItem("显示文字内容3","value值3");
items.Add(item);
comboBoxGroup.DisplayMember = "Name";
comboBoxGroup.ValueMember = "Id";
comboBoxGroup.DataSource = items;
this.comboBoxGroup.SelectedIndex = 0;
//下拉框事件
comboBoxGroup.SelectedIndexChanged += new EventHandler(comboBoxGroup_SelectedIndexChanged);
return 0;
}
搞定~
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询