简体   繁体   English

将列表数组中的值绑定到列表框

[英]Bind values from a list array to listbox

任何正文都可以给出一个简短的例子,用于将列表数组中的值绑定到c#.net中的列表框

It depends on how your list array is. 这取决于列表数组的方式。

Let's start from an easy sample: 让我们从一个简单的样本开始:

List<string> listToBind = new List<string> { "AA", "BB", "CC" };
this.listBox1.DataSource = listToBind;

Here we have a list of strings, that will be shown as items in the listbox. 这里我们有一个字符串列表,它将在列表框中显示为项目。

替代文字

Otherwise, if your list items are more complex (eg custom classes) you can do in this way: 否则,如果您的列表项更复杂(例如自定义类),您可以这样做:

Having for example, MyClass defined as follows: 例如, MyClass定义如下:

public class MyClass
{
    public int Id { get; set; }
    public string Text { get; set; }
    public MyClass(int id, string text)
    {
        this.Id = id;
        this.Text = text;
    }
}

here's the binding part: 这是绑定部分:

List<MyClass> listToBind = new List<MyClass> { new MyClass(1, "One"), new MyClass(2, "Two") };
this.listBox1.DisplayMember = "Text";
this.listBox1.ValueMember = "Id"; // optional depending on your needs
this.listBox1.DataSource = listToBind;

And you will get a list box showing only the text of your items. 您将获得一个列表框,仅显示您的项目文本。 Setting also ValueMember to a specific Property of your class will make listBox1.SelectedValue containing the selected Id value instead of the whole class instance. ValueMember设置为类的特定属性将使listBox1.SelectedValue包含所选的Id值而不是整个类实例。

NB NB
Letting DisplayMember unset, you will get the ToString() result of your list entries as display text of your ListBox items. DisplayMember取消设置,您将获得列表条目的ToString()结果作为ListBox项目的显示文本。

替代文字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM