简体   繁体   English

如何从类的通用列表设置列表框的数据源

[英]How to set datasource of listbox from generic list of class

How can I bind List to the datasource of a Listbox? 如何将List绑定到Listbox的数据源? I want to to set the visible property Name. 我想设置可见属性Name。

Here is my class and list: 这是我的课程和清单:

 public class Users
 {
    public string Name { get; set; }
    public DateTime Data { get; set; }
    public int Id { get; set; }
    public Users()
    {
        Name = null;
        Data = DateTime.Now;
        Id = 0;
    }
    public Users(string N,DateTime dateTime, int id)
    {
        Name = N;
        Data = dateTime;
        Id = id;
    }
}

Here is how I try to bound the datasource: 这是我尝试绑定数据源的方法:

        ListBox1.DataSource = ((List<Users>) Application["Users_On"]);
        ListBox1.DataBind();
  ListBox1.DataSource = ((List<Users>) Application["Users_On"]);
  ListBox1.DataTextField = "Name";
  ListBox1.DataBind();

You can use the DataTextField property of the ListBox class to display the Name propperty of your object. 您可以使用ListBox类的DataTextField属性显示对象的名称属性。

Alex, not really sure how you are trying to generate and bound the values, I'll try to simplify, lets say I have a class called GenericLists , where I'll declare all the reusable generic data, let's assume products for example so I can do like this : Alex,不是很确定您是如何尝试生成和绑定值的,我将尝试简化一下,假设我有一个名为GenericLists的类,在此我将声明所有可重用的通用数据,让我们假设使用产品,例如可以这样:

private Dictionary<int, string> relatedProducts { set; get;}
public Dictionary<int, string> relatedProductsList { 
        get {return relatedProducts; } 
    }

public GenericLists()
{
        relatedProducts = new Dictionary<int, string>
            {
                    {0, "CTRL + Click to select multiples"},
                    {1, "A"},
                    {2, "B"},
                    {3, "C"},
                    {4, "D"},
             };
}

And now I want to bind it to a listbox in any form : 现在,我想以任何形式将其绑定到列表框:

  GenericLists gList = new GenericLists();

            products.DataSource = gList.relatedProductsList;
            products.DataValueField = "Key";
            products.DataTextField = "Value";
            products.DataBind();

I hope this would give you an idea. 我希望这会给您一个想法。

Good Luck 祝好运

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

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