【问题标题】:How do I set values for the entries in a Windows Forms ComboBox?如何为 Windows 窗体组合框中的条目设置值?
【发布时间】:2014-07-28 08:58:45
【问题描述】:

我想要一个包含 12 个选项的下拉列表。

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

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

如您所见,我只能输入选项的名称,但不能输入它的值。

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

我尝试过的

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

有没有更好的办法?

【问题讨论】:

  • 这是否连接到数据集?你说的价值观是什么意思? DisplayMember 不是价值吗? - 它是您想要作为值的数据库中的 ID 吗?
  • @KidCode 不,它没有连接到任何数据源,这些只是静态选择,永远不会改变

标签: winforms combobox windows-forms-designer


【解决方案1】:

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

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

    }

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

【讨论】:

  • 我注意到我发布的代码中有一些不一致的地方,我已经编辑了我的答案,以便您更容易理解!
【解决方案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;

【讨论】:

  • comboxBox1.DisplayMember 一定是列表而不是字符串吧?
  • DisplayMember 是源上应显示的属性的名称。
  • 我在这一行 Object reference not set to an instance of an object. 收到了这个异常 int selectedValue = (int)comboBox1.SelectedValue;
  • 为您的努力+1,但其他答案对我有更好的帮助。谢谢
猜你喜欢
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 2015-09-12
相关资源
最近更新 更多