在WFA中将文本和值都设置为ComboBox项

时间:2013-09-30 01:07:57

标签: c# .net winforms

我有一个Web应用程序,其中显示了一个项目列表(listItem)。对于每个元素,我分配其文本和值。

我可以使用SelectedValue检索该值。

我现在正在将此网页构建为WFA,到目前为止,我只能将文本分配给每个comboBox项目。

我想为它添加一个值(这将是数据库中的id),因此我可以使用该值来有效地更新/删除等。

你们会怎么做呢?

由于

1 个答案:

答案 0 :(得分:0)

您习惯使用的属性在Winforms中不存在,但由于ComboBox接受了一个对象,您可以使用所需的属性创建自己的自定义类。我已经在ListControl.DisplayMember Property上获取了MSDN文档,并将其作为示例进行了修改。

它的作用是创建一个名为customComboBoxItem的自定义类,其中包含TextValue属性,然后创建一个列表并将其指定为您的DataSource ComboBoxText属性指定为DisplayMember。看看这是否适合您。

public partial class Form1 : Form
{
    List<customComboBoxItem> customItem = new List<customComboBoxItem>();

    public Form1()
    {
        InitializeComponent();
        customItem.Add(new customComboBoxItem("text1", "id1"));
        customItem.Add(new customComboBoxItem("text2", "id2"));
        customItem.Add(new customComboBoxItem("text3", "id3"));
        customItem.Add(new customComboBoxItem("text4", "id4"));
        comboBox1.DataSource = customItem;
        comboBox1.DisplayMember = "Text";
        comboBox1.ValueMember = "Value";

    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        MessageBox.Show( ((customComboBoxItem)comboBox1.SelectedItem).Text + " " 
                         + ((customComboBoxItem)comboBox1.SelectedItem).Value); 
    }
}

public class customComboBoxItem
{
    private string text;
    private string value;

    public customComboBoxItem(string strText, string strValue)
    {
        this.text = strText;
        this.value = strValue;

    }

    public string Text
    {
        get { return text; }
    }

    public string Value
    {
        get { return value; }
    }

}