Fill a pair of data (text and value) to ComboBox .NET 2.0 Windows Application

2008-09-04


In .NET 2.0 Windows Application, It is not easy to fill a pair of data (text, value) to a ComboBox, Most of examples just introduced the Display member and value member:

comboBox1.DisplayMember = "Desc";
comboBox1.ValueMember = "Code";
comboBox1.DataSource = dt;

Now let us don't use DataSource and DisplayMember way:

class CmdPairClass
{
    private string _cmdLongStr;
    public string CommandLongString
    {
        get { return _cmdLongStr; }
        set { _cmdLongStr = value; }
    }

    private string _cmdShortStr;
    public string CommandShortString
    {
        get { return _cmdShortStr; }
        set { _cmdShortStr = value; }
    }



    public CmdPairClass(string s1, string s2)
    {
        this.CommandLongString = s1;
        this.CommandShortString = s2;

    }

    public override string ToString()
    {
        
        return CommandLongString;
    }
}

    List<CmdPairClass> aCmdPairList = new List<CmdPairClass>();
  


    public MForm()
    {
        InitializeComponent();

        aCmdPairList.AddRange( new CmdPairClass[] { 
            new CmdPairClass( "Power", "PW" ), 
            new CmdPairClass( "Remote", "RM")
            });
    }


 ....

        for (int i = 0; i < aCmdPairList.Count; i++)
        {

            this.cbCmdType.Items.Add(new CmdPairClass(aCmdPairList[i].CommandLongString, aCmdPairList[i].CommandShortString)); 

        }


    private void cbCmdType_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lbMessage.Items.Add(((CmdPairClass)this.cbCmdType.SelectedItem).CommandShortString + "\r\n");

        this.lbMessage.Update();


    }