日期:2014-05-18  浏览次数:21100 次

如何将winform中的listbox 与 hashtable绑定
System.Collections.Hashtable hash = new System.Collections.Hashtable();
  for (int i = 0; i < 10; i++)
  {
  hash.Add(i.ToString(), "value:" + i.ToString());
  }
   
  //将HASH绑到LISTBOX  
  System.Collections.IDictionaryEnumerator myEnumerator = hash.GetEnumerator();
  while (myEnumerator.MoveNext())
  {  
  listBox1.Items.Add(myEnumerator.Value);
  }
  }

现在LISTBOX只能显示信息,不能将KEY绑到上面,而直接用下面语句,会出错
  this.listBox1.DataSource = hash;
  this.listBox1.DisplayMember = "Key";
  this.listBox1.ValueMember = "Value";

------解决方案--------------------
使用结构体或类来做为ListBox的Items的元素,重写结构体或类的ToString方法显示文本。可以使用List<T>来存放Items并把List<T>绑到ListBox上,或通过循环添加到ListBoix上,取元素的时候对元素进行强制转换就可以了。比如:
C# code

        public class item
        {
            private object m_Value;
            private string m_Text;

            public item(object value, string text)
            {
                this.m_Value = value;
                this.m_Text = text;
            }
            public object Value
            {
                get { return m_Value; }
            }

            public string Text
            {
                get { return m_Text; }
            }
            public override string ToString()
            {
                return this.m_Text;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            List<item> list = new List<item>();
            for (int i = 0; i < 10; i++)
            { 
                list.Add(new item(i, "item" + i.ToString()));
            }
            this.listBox1.DataSource = list;
        }
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);

            item _item = this.listBox1.Items[this.listBox1.SelectedIndex] as item;
            if (_item != null)
            {
                Console.WriteLine(_item.Value);
            }
        }

------解决方案--------------------
C# code
 
System.Collections.Hashtable  hash  =  new  System.Collections.Hashtable();
for  (int  i  =  0;  i  <  10;  i++)
{
hash.Add(i.ToString(),  "value:"  +  i.ToString());
}
         
//将HASH绑到LISTBOX 
System.Collections.IDictionaryEnumerator  myEnumerator  =  hash.GetEnumerator();
DataTable dtTemp=new DataTable();
dtTemp.Columns.Add("key",typeof(string));
dtTemp.Columns.Add("value",typeof(string));
DataRow drTemp=null;
while (myEnumerator.MoveNext())
{             
drTemp=dtTemp.NewRow();
drTemp["key"]=myEnumerator.Key;
drTemp["value"]=myEnumerator.Value;
dtTemp.Rows.Add(drTemp);
}
this.listBox1.DataSource=dtTemp;
listBox1.DisplayMember="key";
listBox1.ValueMember="value";

------解决方案--------------------
Hashtable has = new Hashtable();
for (int i = 0; i < 10; i++)
{
DataTable dt = new DataTable();
dt.Columns.Add("Key");