在C#WinForm中向ComboBox添加值

时间:2013-08-17 22:16:14

标签: c# winforms combobox

我正在尝试为组合框添加一个值。我可以设置文本,但不能设置值。我知道我可以使用数据表填充组合框,但我想手动完成以完全控制数据显示。我可以做ComboBox.Items.Add(),但这只是设置文本。如何添加值(将是主键,与文本不同)?

    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();
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

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