如何为Windows窗体组合框中的条目设置值?

时间:2014-07-28 08:58:46

标签: winforms combobox windows-forms-designer

我希望有一个包含12个选项的下拉列表。

我发现ComboBox是我需要的(如果有更好的控制,请告诉我)。

我使用VS2012将组合框拖放到面板中,然后单击组合框上显示的左箭头。以下向导显示:

enter image description here

正如您所看到的,我只能输入选择的名称,而不能输入它的值。

我的问题是如何获得这些选择的价值?

我尝试了什么

我构建了一个与选项长度相同的数组,所以当用户选择任何选项时,我会得到该选择的位置并从该数组中获取值。

有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

您需要使用数据表,然后从中选择值。 例如)

        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Description", typeof(string));
        dt.Load(reader);
        //Setting Values
        combobox.ValueMember = "ID";
        combobox.DisplayMember = "Description";
        combobox.SelectedValue = "ID";
        combobox.DataSource = dt;

然后您可以使用以下方法填充数据表:

 dt.Rows.Add("1","ComboxDisplay");

此处,DisplayMember(下拉列表项)为Descriptions,值为ID

您需要添加一个' SelectedIndexChanged'组合框上的事件(如果使用VS然后在设计模式下双击控件)以获取新值。类似的东西:

 private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int ID = Combobox.ValueMember;
        string Description = ComboBox.DisplayMember.ToString();

    }

然后,您可以在其余代码中使用这些变量。

答案 1 :(得分:2)

您无法使用向导存储值和文本。要存储DisplayText / Value对,需要将组合框连接到某些数据。

public class ComboboxItem
{
    public string DisplayText { get; set; }
    public int Value { get; set; }            
}

组合框有两个属性 - DisplayMember和ValueMember。我们使用这些来告诉组合框 - 在DisplayMember中显示什么,实际值在ValueMember中。

private void DataBind()
{
    comboBox1.DisplayMember = "DisplayText";
    comboBox1.ValueMember = "Value";

    ComboboxItem item = new ComboboxItem();
    item.DisplayText = "Item1";
    item.Value = 1;

    comboBox1.Items.Add(item);       
}

获取值 -

 int selectedValue = (int)comboBox1.SelectedValue;