C#WinForm开发之在ComboBox、ListBox中加载键值对

来源:互联网 发布:知乎 委员 葫芦娃 编辑:程序博客网 时间:2024/05/21 19:47

      经常,我们会有这样的需要:

               给ComboBox或者ListBox添加项时,我们希望同时添加值和名字。

      但是,C#本身并没有提供这种机制,但是ComboBox和ListBox都具有DisplayMember和 ValueMember属性。因此,需要我们自己根据C#本身提供的一下接口,来实现这个功能需求。

 

      通过查资料,整理出一个解决方案:

          定义一个键值对类型,其实例作为ComboBox和ListBox的一个Item;

 

 

      具体实现如下(以ComboBox为例进行说明):

 

1、添加选项类: 

/// <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;
  }

  /*combobox的 Item.ADD(一个任意类型的变量),而显示的时候调用的是这个变量的ToString()方法,如果这个类没有重载ToString(),那么显示的结果就是命名空间   +   类名*/
  

 

 


  

public string ID 
  { 
   
get
   {
    
return this.id;
   } 
   
set
   {
    
this.id = value;
   } 
  } 

 

 


  
public string Name 
  { 
   
get
   {
    
return this.name;
   } 
   
set
   {
    
this.name = value;
   } 
  } 
 }

 

2、为ComboBox添加项:

ListItem item = new ListItem("id:key""name:value");
cbb.Items.Add(item);
cbb.DisplayMember = "Name";
cbb.ValueMember = "ID";

 

3、使用ComboBox当前项:

ListItem item = (ListItem)cbb.SelectedItem;

string sId=item.ID.ToString().Trim();

string sName=item.Name.ToString().Trim();

4、获取已知项在ComboBox中的索引

ListItem item = new ListItem("id:key""name:value");

cbb.SelectedIndex = cbb.FindString(item.Name.ToString().Trim());

 

特别说明:本文重点参考http://blog.csdn.net/fcsh820/archive/2009/02/07/3867053.aspx