在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:

combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"

当前回答

这是我想到的方法之一:

combo1.Items。添加(new ListItem("Text", "Value"))

要更改一个项目的文本或值,你可以这样做:

combo1.Items[0].Text = 'new Text';

combo1.Items[0].Value = 'new Value';

在Windows窗体中没有名为ListItem的类。它只存在于ASP中。因此,在使用它之前,您需要编写自己的类,就像@Adam Markowitz在他的回答中所做的一样。

还可以查看这些页面,它们可能会有帮助:

如何将项目添加到组合框 如何:从Windows窗体组合框、列表框或checkkedlistbox控件中添加和删除项

其他回答

// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
        test.Add("1", "dfdfdf");
        test.Add("2", "dfdfdf");
        test.Add("3", "dfdfdf");
        comboBox1.DataSource = new BindingSource(test, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";

// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;

您可以使用字典对象,而不是创建自定义类来在组合框中添加文本和值。

在Dictionary对象中添加键和值:

Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");

将源Dictionary对象绑定到Combobox:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

检索键和值:

string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;

完整来源:组合框文本和值

using (SqlConnection con = new SqlConnection(insertClass.dbPath))
{
    con.Open();
    using (SqlDataAdapter sda = new SqlDataAdapter(
    "SELECT CategoryID, Category FROM Category WHERE Status='Active' ", con))
    {
        //Fill the DataTable with records from Table.
        DataTable dt = new DataTable();
        sda.Fill(dt);
        //Insert the Default Item to DataTable.
        DataRow row = dt.NewRow();
        row[0] = 0;
        row[1] = "(Selecione)";
        dt.Rows.InsertAt(row, 0);
        //Assign DataTable as DataSource.
        cboProductTypeName.DataSource = dt;
        cboProductTypeName.DisplayMember = "Category";
        cboProductTypeName.ValueMember = "CategoryID";
    }
}             
con.Close();
//set 
comboBox1.DisplayMember = "Value"; 
//to add 
comboBox1.Items.Add(new KeyValuePair("2", "This text is displayed")); 
//to access the 'tag' property 
string tag = ((KeyValuePair< string, string >)comboBox1.SelectedItem).Key; 
MessageBox.Show(tag);

这里有更好的解决方案;

Dictionary<int, string> userListDictionary = new Dictionary<int, string>();
        foreach (var user in users)
        {
            userListDictionary.Add(user.Id,user.Name);
        }

        cmbUser.DataSource = new BindingSource(userListDictionary, null);
        cmbUser.DisplayMember = "Value";
        cmbUser.ValueMember = "Key";

检索数据

MessageBox.Show(cmbUser.SelectedValue.ToString());