linq绑定下拉列表,combobox中增加listitem的方法,增加“请选择”
第一步:自定义一个类ListItem
public class ListItem
{
private string text = string.Empty;
private string value = string.Empty;
public ListItem(string Text, string Value)
{
text = Text;
value = Value;
}
public override string ToString()
{
return this.value;
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
public string Value
{
get
{
return this.value;
}
set
{
this.value = value;
}
}
}
第二步:采用linq查询数据并绑定到combobox,解决很多人想问的增加默认选项“请选择”的问题
private void BindRadioType()
{
cmbRadioType.DataSource = null;
cmbRadioType.Items.Clear();
using (DCDataBaseDataContext db = new DCDataBaseDataContext())
{
var query = (from c in db.Items_RadioType
select new{c.ItemName,c.Id}
).ToList();
List<ListItem> items = new List<ListItem>();
foreach (var temp in query)
{
items.Add(new ListItem(temp.ItemName,temp.Id.ToString()));
}
items.Insert(0, new ListItem("请选择", "-1"));
cmbRadioType.DataSource = items;
cmbRadioType.DisplayMember = "Text";
cmbRadioType.ValueMember = "Value";
}
}