winform中ComboBox和ListBox添加选项的方法

本文介绍了一种在WinForm应用程序中为ComboBox控件自定义选项的方法,通过创建ListItem类并重载ToString()方法实现更灵活地添加和显示选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.net开发winform应用程序,用comboBox的数据绑定的方法很简单,建一个数据源,绑定到ComboBox上,然后指定DisplayMember和 ValueMember就可以了。但是感觉不灵活,如果我要在ComboBox上再添加一选项,那怎么办?

 

Web里面有ListItem, winform里面怎么没有了?感觉真是不爽,网上找了个方法,自己添加一个ListItem类,然后add到items里面,感觉还不错,有点象web 里面的用法了,可是问题又来了,添加的第一项怎么变成类名了?不是我给它赋的名字,其他项又都没有问题。于是又查到说,“因为combobox的 Item.ADD(一个任意类型的变量),而显示的时候调用的是这个变量的ToString()方法,如果这个类没有重载ToString(),那么显示的结果就是命名空间 + 类名”,于是加上重载的ToString()方法,好了,至此,我终于可以很方便的来给ComboBox和ListBox添加项了。

 

首先添加类ListItem:

 

ContractedBlock.gifExpandedBlockStart.gif代码
/// <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;

  }

 }

}

 

 

然后在程序中使用:

 

ListItem item = new ListItem("", "");

this.lbChoiceRoom.Items.Add(item);

this.lbChoiceRoom.DisplayMember = "Name";

this.lbChoiceRoom.ValueMember = "ID";

 

 

 

取值方法:

 

MessageBox.Show(((ListItem)lbChoiceRoom.SelectedItem).ID);

 

转载于:https://www.cnblogs.com/Sue_/articles/1723905.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值