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

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

当前回答

这是一个非常简单的解决方案为windows窗体,如果所有需要的是最终值(字符串)。项目的名称将显示在组合框上,选择的值可以很容易地进行比较。

List<string> items = new List<string>();

// populate list with test strings
for (int i = 0; i < 100; i++)
            items.Add(i.ToString());

// set data source
testComboBox.DataSource = items;

并在事件处理程序上获取所选值的值(字符串)

string test = testComboBox.SelectedValue.ToString();

其他回答

这是我想到的方法之一:

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控件中添加和删除项

这是一个非常简单的解决方案为windows窗体,如果所有需要的是最终值(字符串)。项目的名称将显示在组合框上,选择的值可以很容易地进行比较。

List<string> items = new List<string>();

// populate list with test strings
for (int i = 0; i < 100; i++)
            items.Add(i.ToString());

// set data source
testComboBox.DataSource = items;

并在事件处理程序上获取所选值的值(字符串)

string test = testComboBox.SelectedValue.ToString();
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();

您应该在运行时使用动态对象来解析组合框项。

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

comboBox.Items.Add(new { Text = "Text", Value = "Value" });

(comboBox.SelectedItem as dynamic).Value

类创造:

namespace WindowsFormsApplication1
{
    class select
    {
        public string Text { get; set; }
        public string Value { get; set; }
    }
}

Form1代码:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            List<select> sl = new List<select>();
            sl.Add(new select() { Text = "", Value = "" });
            sl.Add(new select() { Text = "AAA", Value = "aa" });
            sl.Add(new select() { Text = "BBB", Value = "bb" });
            comboBox1.DataSource = sl;
            comboBox1.DisplayMember = "Text";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            select sl1 = comboBox1.SelectedItem as select;
            t1.Text = Convert.ToString(sl1.Value);

        }

    }
}