从列表中数组绑定值列表框 [英] Bind values from a list array to listbox

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

问题描述

任何正文都可以给出一个简单的例子,用于将c#.net

解决方案中的值从list数组绑定到listbox



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

  List< 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),new MyClass(2,Two)}; 
this.listBox1.DisplayMember =Text;
this.listBox1.ValueMember =Id; //可选取决于你的需要
this.listBox1.DataSource = listToBind;

你会得到一个只显示项目文本的列表框。
设置 ValueMember 到您的类的特定属性将使 listBox1.SelectedValue 包含所选的<$



NB

DisplayMember 取消设置,您将获得列表条目的 ToString()结果作为您的 ListBox 项目。




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天全站免登陆