C# 使 ListBox 项目具有与项目文本不同的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/867514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:51:30  来源:igfitidea点击:

Make ListBox items have a different value than item text

c#winforms

提问by CasperT

I want a ListBoxfull of items. Although, each item should have a different value. So when the user selects an item and presses a button, a method will be called which will use the value the select item has.

我想要ListBox满满的物品。虽然,每个项目应该有不同的价值。因此,当用户选择一个项目并按下按钮时,将调用一个方法,该方法将使用选择项目的值。

I don't want to reveal the item values to the user.

我不想向用户透露项目值。

EDIT:This is not for ASP.NET, it's for a Windows Forms application. I just thought the HTML example would be easy to read.

编辑:这不适用于 ASP.NET,它适用于 Windows 窗体应用程序。我只是认为 HTML 示例很容易阅读。

I have the inspiration from HTML:

我的灵感来自 HTML:

<form>
<input type="radio" name="sex" value="Value1" /> Male
<br />
<input type="radio" name="sex" value="Value2" /> Female
</form>

This also allows me to use different values than what the user sees.

这也允许我使用与用户看到的不同的值。

采纳答案by Fredrik M?rk

You can choose what do display using the DisplayMember of the ListBox.

您可以使用 ListBox 的 DisplayMember 选择要显示的内容。

List<SomeData> data = new List<SomeData>();
data.Add(new SomeData() { Value = 1, Text= "Some Text"});
data.Add(new SomeData() { Value = 2, Text = "Some Other Text"});
listBox1.DisplayMember = "Text";
listBox1.DataSource = data;

When the user selects an item, you can read the value (or any other property) from the selected object:

当用户选择一个项目时,您可以从所选对象中读取值(或任何其他属性):

int value = (listBox1.SelectedItem as SomeData).Value;

Update: note that DisplayMember works only with properties, not with fields, so you need to alter your class a bit:

更新:请注意 DisplayMember 仅适用于属性,不适用于字段,因此您需要稍微更改您的类:

public class SomeData
{
    public string Value { get; set; };
    public string Text { get; set; };
}

回答by second

items have a property called 'Tag', which you can use to store any information you want (hidden from the user)

项目有一个名为“标签”的属性,您可以使用它来存储您想要的任何信息(对用户隐藏)

ListViewItem myItem = new ListViewItem();
myItem.Text = "Users see this";
myItem.Tag = "Users don't see this";

(or set the appropriate properties in the property explorer)

(或在属性浏览器中设置适当的属性)

回答by odalet

As stated by the 1st answer, the use of DisplayMemberworks whether you are using asp.net or winforms.

正如第一个答案所述,DisplayMember无论您使用的是asp.net还是winforms,都可以使用作品。

And to comment a bit more, it also works if you are using the rather old fashion Items.addway of adding items to a ListBox.

并且要多加评论,如果您使用相当古老的Items.add方式将项目添加到ListBox.

Just for fun, here is a simple demo of what you need (just create a new form and drop on it a ListBox and a Label):

只是为了好玩,这里是您需要的简单演示(只需创建一个新表单并在其上放置一个 ListBox 和一个标签):

public partial class Form1 : Form
{
    class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public override string ToString()
        {
            return string.Format("{0} {1}", LastName, FirstName);
        }
    }

    public Form1() { InitializeComponent(); }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);                        
        listBox1.DisplayMember = "LastName";            
        listBox1.DataSource = GetCustomers();
        //listBox1.Items.AddRange(GetCustomers().ToArray());            
    }

    private IEnumerable<Customer> GetCustomers()
    {
        return new List<Customer>()
        {
            new Customer() { FirstName = "Gustav", LastName = "MAHLER" },
            new Customer() { FirstName = "Johann Sebastian", LastName = "BACH" }
        };
    }

    private void lb_SelectedIndexChanged(object sender, EventArgs e)
    {
        label1.Text = listBox1.SelectedItem.ToString();
    }        
}

Enjoy

享受

PS: @2nd postTagis not available to ListBox: because it accepts an array of object, not a specific item container like ListView... but you don't need any in your case. Tagis useful when you want to carry additional data along with a specific TreeViewItemor ListViewItemfor example. By the way, Tagis defined at the Controllevel and so exists for Button, Label, and so on... but for my part I think it is rather a bad idea to store business data in it (untyped, UI coupled...) apart from the ListViewand TreeViewcases for which it is rather convenient.

PS:@2nd postTag不可用于ListBox:因为它接受一个数组object,而不是一个特定的项目容器,比如ListView......但在你的情况下你不需要任何容器。Tag当您想要携带附加数据以及特定数据TreeViewItemListViewItem例如时非常有用。顺便说一下,Tag是在Control级别定义的,因此存在于Button,Label等......但就我而言,我认为将业务数据存储在其中(无类型、UI 耦合......)在ListViewTreeView案件为它是相当方便的。

回答by cexars

Easy!

简单!

protected void Page_Load(object sender, EventArgs e)
    {
        llenaListBox(ListBox1, 0, 10);
    }

    private void llenaListBox(ListBox PoListBox, int PiMinimo, int PiMaximo)
    {
        int Li;
        for (Li = PiMinimo; Li <= PiMaximo; Li++)
        {
            ListItem obj = new ListItem();
            obj.Text  = Li.ToString();
            obj.Value = Li.ToString();
            PoListBox.Items.Add(obj);
        }

    }

回答by iTai Ortix

Very simple:

很简单:

foreach(var item in *Your Source List*)
        {
            ListItem dataItem =  new ListItem();
            dataItem.Text = "value to show";
            dataItem.Value = *another value you want*;
            listBox.Items.Add(dataItem);
        }