WinForm 中ComboBox 绑定总结

1.DataTable绑定

用DataTable直接绑定,只需要设置DataSource、DisplayMember、ValueMember三个属性即可。

this.cmbConsume.DataSource = dtSuperMarket;
this.cmbConsume.DisplayMember = "Name"; 
this.cmbConsumet.ValueMember = "ID";
this.cmbConsume.SelectedIndex = 0;   //选中第一项

在使用时使用如下方式,即可取得相应的ID和Name:

string id = this.cmbConsume.SelectedValue;
string name = this.cmbConsume.SelectedText;

2.ComboBox.Items.Add

一开始使用时,以为像Asp.net那样有ListItem属性可以使用,但Items只有几个特别简单的属性,还好Add(object item),所以就只能在object这里作文章了。

所以就把要绑定的item新new 了一个对象,再重写ToString(),如是乎就可以了。写一个ListItem类:

/// <summary>
 /// ListItem用于ComboBox控件添加项
 /// </summary>
 public class ListItem
 {
     public string Text
     {
         get;
         set;
     }
     public string Value
     {
         get;
         set;
     }

     public override string ToString()
     {
         return this.Text;
     }
 }
   
private void Test()
{
    ListItem item = new ListItem();
    item.Text = "Item text1";
    item.Value = 12;

    comboBox1.Items.Add(item);

    comboBox1.SelectedIndex = 0;

    MessageBox.Show((comboBox1.SelectedItem as ListItem).Value.ToString());
}
原文地址:https://www.cnblogs.com/weekend001/p/3516770.html