在 WFA 中将文本和值设置为 ComboBox 项 [英] Setting both text and value to ComboBox items in WFA
问题描述
我有一个 Web 应用程序,我在其中显示项目列表 (listItem).我为每个元素分配文本和值.
I have a web application in which I display a list of items (listItem). To each element, I assign its text and a value.
我可以使用 SelectedValue 检索值.
I can retrieve the value by using SelectedValue.
我现在将此网页构建为 WFA,到目前为止我只能将文本分配给每个组合框项目.
I am now building this web page as a WFA, and so far I am only able to assign the text to each comboBox items.
我想向它添加一个值(这将是数据库中的一个 id),这样我就可以使用该值来有效地更新/删除等.
I would like to add a value to it (which would be an id from the database), so I can then use that value to efficiently update/delete etc.
你们会怎么做?
谢谢
推荐答案
Winforms 中不存在您习惯的属性,但由于 ComboBox
接受一个对象,您可以创建自己的具有您需要的属性的自定义类.我已经在 ListControl.DisplayMember 上获取了 MSDN 文档属性,并以修改为例.
The properties that you are used to are not present in Winforms, but since the ComboBox
takes an object, you can make your own Custom Class with the Properties that you need. I have taken the MSDN Documentation on the ListControl.DisplayMember Property and modified it as an example.
它的作用是创建一个名为 customComboBoxItem
的自定义类,其中包含一个 Text
和一个 Value
属性,然后我创建一个 List 并分配它作为 ComboBox
的 DataSource
,将 Text
属性指定为 DisplayMember.看看这对你是否可行.
What it does is create a custom class called customComboBoxItem
with a Text
and a Value
Property, I then make a List and assign it as the DataSource
of your ComboBox
assigning the Text
Property as the DisplayMember. See if this is workable for you.
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; }
}
}
这篇关于在 WFA 中将文本和值设置为 ComboBox 项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!