0

I am trying to add a value to a combobox. I can set the text, but not the value. I know I can populate the combobox with a datatable, but I want to do it manually to keep full control of the data display. I can do the ComboBox.Items.Add(), but that just sets the text. How do I add the value (which will be a primary key, different from the text)?

    public Form1()
    {
        InitializeComponent();
        OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Drew\Documents\Visual Studio 2012\Projects\Football\Football\db\FB_DB.mdb;User Id=admin;Password=;");

        //Load QB DropDown
        conn.Open();
        OleDbCommand cmd = new OleDbCommand("select PlayerID,LastName,FirstName from tb_players where Pos = 'QB' Order By LastName", conn);
        OleDbDataReader reader = cmd.ExecuteReader();

        string plyrName = "";

        while (reader.Read())
        {
            plyrName = reader["LastName"].ToString() + ", " + reader["FirstName"].ToString();
            cbQb.Items.Add(plyrName);
        }
        conn.Close();
    }
4

1 回答 1

1

尝试这个:

public Form1()
{
    InitializeComponent();
    OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Drew\Documents\Visual Studio 2012\Projects\Football\Football\db\FB_DB.mdb;User Id=admin;Password=;");

    //Load QB DropDown
    conn.Open();
    OleDbCommand cmd = new OleDbCommand("select PlayerID,LastName,FirstName from tb_players where Pos = 'QB' Order By LastName", conn);
    OleDbDataReader reader = cmd.ExecuteReader();

    string plyrName = "";
    int keyValue;

    cbQb.DisplayMember = "Value";
    cbQb.ValueMember = "Key";

    while (reader.Read())
    {
        plyrName = reader["LastName"].ToString() + ", " + reader["FirstName"].ToString();
        index = Convert.ToInt32(reader["primaryKeyColumnValue"]);

        KeyValuePair<int, string> cmbItem = new KeyValuePair<int, string> (index ,plyrName)
        cbQb.Items.Add(cmbItem);
    }
    conn.Close();
}

您可以像这样获取所选项目的键的值:

((KeyValuePair<int, string>)cbQb.SelectedItem).Key
于 2013-08-17T22:44:35.560 回答