将列表数组绑定到列表框 [英] Bind values from a list array to listbox

查看:137
本文介绍了将列表数组绑定到列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

这取决于哪个机构可以将列表数组中的值绑定到列表框中?关于你的列表数组的方式。



我们从一个简单的例子开始:

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

这里我们有一个字符串列表,它将显示为列表框中的项目。 >



否则,如果您的列表项更复杂(例如自定义类),您可以这样做:



例如, MyClass 定义如下:

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

这里是绑定部分:

 列表< MyClass> listToBind = new List< MyClass> {new MyClass(1,One),新的MyClass(2,Two)}; 
this.listBox1.DisplayMember =Text;
this.listBox1.ValueMember =Id; //根据需要选择
this.listBox1.DataSource = listToBind;

您将会收到一个仅显示您的项目文本的列表框。
ValueMember 设置为您的类的特定属性将使 listBox1.SelectedValue 包含所选的 id 值而不是整个类实例。



NB

DisplayMember unset,您将获得列表条目的 ToString()结果作为 ListBox items。




Could any body give a short example for binding a value from list array to listbox in 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 (e.g. custom classes) you can do in this way:

Having for example, MyClass defined as follows:

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.

N.B.
Letting DisplayMember unset, you will get the ToString() result of your list entries as display text of your ListBox items.

这篇关于将列表数组绑定到列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆