zoukankan      html  css  js  c++  java
  • 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());
    }
  • 相关阅读:
    luogu P1833 樱花 看成混合背包
    luogu P1077 摆花 基础记数dp
    luogu P1095 守望者的逃离 经典dp
    Even Subset Sum Problem CodeForces
    Maximum White Subtree CodeForces
    Sleeping Schedule CodeForces
    Bombs CodeForces
    病毒侵袭持续中 HDU
    病毒侵袭 HDU
    Educational Codeforces Round 35 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/weekend001/p/3516770.html
Copyright © 2011-2022 走看看