国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#(WinForm) ComboBox和ListBox添加項及設置默認選擇項

2020-01-24 02:38:51
字體:
來源:轉載
供稿:網友

Web控件DropDownList和WinForm控件ComboBox機制不一樣。
ComboBox沒有對應的ListItem需要自己寫一個:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace WinListItem{  /// <summary>  /// 選擇項類,用于ComboBox或者ListBox添加項  /// </summary>  public class ListItem  {    private string id = string.Empty;    private string name = string.Empty;    public ListItem(string sid, string sname)    {      id = sid;      name = sname;    }    public override string ToString()    {      return this.name;    }    public string ID    {      get      {        return this.id;      }      set      {        this.id = value;      }    }    public string Name    {      get      {        return this.name;      }      set      {        this.name = value;      }    }  }}

然后可以類似DropDownList添加項:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace WinListItem{  public partial class MainFrm : Form  {    public MainFrm()    {      InitializeComponent();    }    private void btnOk_Click(object sender, EventArgs e)    {      ListItem listItem = comboBox1.SelectedItem as ListItem;      MessageBox.Show(listItem.ID + "," + listItem.Name);    }    private void MainFrm_Load(object sender, EventArgs e)    {      //添加項,Web控件DropDownList有對應的ListItem      ListItem listItem0 = new ListItem("0", "選項零");      ListItem listItem1 = new ListItem("1", "選項一");      ListItem listItem2 = new ListItem("2", "選項二");      comboBox1.Items.Add(listItem0);      comboBox1.Items.Add(listItem1);      comboBox1.Items.Add(listItem2);      //設置默認選擇項,DropDownList會默認選擇第一項。      comboBox1.SelectedIndex = 0;//設置第一項為默認選擇項。      comboBox1.SelectedItem = listItem1;//設置指定的項為默認選擇項    }  }}

運行如圖:

參考:c#(winform)中ComboBox和ListBox添加項完全解決

剛開始用.net 的winform開發,發現好些控件都很難用,可能是不熟悉的原因吧,這不,一個給ComboBox添加項的問題就搞的我很頭疼,我要同時給一個項添加名字和值,怎么都沒法加,查了查資料,又自己匯總測試了下,終于全部搞定了,現把完整的方案寫下。

用comboBox的數據綁定的方法很簡單,建一個數據源,綁定到ComboBox上,然后指定DisplayMember和 ValueMember就可以了。但是感覺好不靈活哦,如果我要在ComboBox上再添加一項,那怎么辦?Web里面有ListItem, winform里面怎么沒有了?感覺真是不爽,網上找了個方法,自己添加一個ListItem類,然后add到items里面,感覺還不錯,有點象web 里面的用法了,可是問題又來了,添加的第一項怎么變成類名了?不是我給它賦的名字,其他項又都沒有問題。于是又查到說,“因為combobox的 Item.ADD(一個任意類型的變量),而顯示的時候調用的是這個變量的ToString()方法,如果這個類沒有重載ToString(),那么顯示的結果就是命名空間 + 類名”,于是加上重載的ToString()方法,好了,至此,我終于可以很方便的來給ComboBox和ListBox添加項了。

復制代碼 代碼如下:

ListItem item = new ListItem("我是值", "我是名字");
this.lbChoiceRoom.Items.Add(item);
this.lbChoiceRoom.DisplayMember = "Name";
this.lbChoiceRoom.ValueMember = "ID";

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 杨浦区| 邮箱| 剑川县| 阿鲁科尔沁旗| 阳曲县| 忻州市| 永新县| 兰考县| 原平市| 马山县| 怀仁县| 青冈县| 博爱县| 宣威市| 吴堡县| 当涂县| 安阳县| 唐河县| 会昌县| 新竹市| 南京市| 瓮安县| 龙岩市| 镇康县| 双辽市| 类乌齐县| 乐至县| 临泽县| 怀宁县| 丰城市| 台山市| 扎囊县| 彰化市| 晋中市| 西吉县| 四会市| 马龙县| 叶城县| 双城市| 蕉岭县| 咸宁市|