ComboBox的下拉选项有两种方式赋值:
1.ComboBox.DataSource ,直接Binding数据源,可以为Table/DataSet/List<T>
2.ComboBox.Items.Add 或ComboBox.Items.Insert. 此方法只有selectedText,而没有selectedValue,所以需要想办法。
void ComboBoxDataBind()
{
IList<InfoTypeTable> list = InfoTypeManager.Select("parentName='reply'");//数据源获取
{
IList<InfoTypeTable> list = InfoTypeManager.Select("parentName='reply'");//数据源获取
//cbbReplyType 为我的第一个ComboBox,通过ComboBox.Items.Add实现
cbbReplyType.Items.Clear();
cbbReplyType.Items.Clear();
cbbReplyType.Items.Insert(0, "所有分类");
foreach (var v in list)
{
cbbReplyType.Items.Add(new ComboBoxItemTextValue(v.id.ToString(), v.typeName));
//cbbReplyType.Items.Insert((int)v.id, v.typeName);
}
cbbReplyType.SelectedIndex = 0;
foreach (var v in list)
{
cbbReplyType.Items.Add(new ComboBoxItemTextValue(v.id.ToString(), v.typeName));
//cbbReplyType.Items.Insert((int)v.id, v.typeName);
}
cbbReplyType.SelectedIndex = 0;
//2.cbbReplyType 为我的第二个ComboBox,通过databinding 实现
cbbTheType.Items.Clear();//cbbReplyType 为我的第二个ComboBox
//将数据源的属性与ComboBox的属性对应
cbbTheType.DisplayMember = "typeName"; //显示
cbbTheType.ValueMember = "id"; //值
cbbTheType.DataSource = list;//list 可以为Table/DataSet/List<T>
}
//将数据源的属性与ComboBox的属性对应
cbbTheType.DisplayMember = "typeName"; //显示
cbbTheType.ValueMember = "id"; //值
cbbTheType.DataSource = list;//list 可以为Table/DataSet/List<T>
}
ComboBox.Insert / ComboBox.Add 只有selectedText,而没有selectedValue.如果需要取Value则需要借助额外的代码。
/// <summary>
/// ComboBoxItemTextValue
/// eg: Add 方法默认只有selectedText,而没有selectedValue
/// Add cbbReplyType.Items.Add(new ComboBoxItemTextValue(v.id.ToString(), v.typeName));
/// Use ComboBoxItemTextValue item = (ComboBoxItemTextValue)cbbReplyType.SelectedItem;
/// </summary>
public class ComboBoxItemTextValue
{
public string selectText;
public string selectValue;
public ComboBoxItemTextValue(string _selectValue, string _selectText)
{
selectValue = _selectValue;
selectText = _selectText;
}
public override string ToString()
{
return selectText;
}
}
/// ComboBoxItemTextValue
/// eg: Add 方法默认只有selectedText,而没有selectedValue
/// Add cbbReplyType.Items.Add(new ComboBoxItemTextValue(v.id.ToString(), v.typeName));
/// Use ComboBoxItemTextValue item = (ComboBoxItemTextValue)cbbReplyType.SelectedItem;
/// </summary>
public class ComboBoxItemTextValue
{
public string selectText;
public string selectValue;
public ComboBoxItemTextValue(string _selectValue, string _selectText)
{
selectValue = _selectValue;
selectText = _selectText;
}
public override string ToString()
{
return selectText;
}
}
希望对大家有用,转载请注明出处。 ---By:五月营销软件 Marin
五月营销软件:五月论坛营销软件、五月百度知道全自动问答软件