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";???????????????
??????????? }?????????
??????? }
?
轉載于:https://www.cnblogs.com/liaofeifan/archive/2011/09/25/2190439.html
總結
以上是生活随笔為你收集整理的linq绑定下拉列表,combobox中增加listitem的方法,增加“请选择”的全部內容,希望文章能夠幫你解決所遇到的問題。