简体   繁体   English

来自 LINQ 查询的 ListBox 数据源

[英]ListBox datasource from LINQ query

Let's say there is a List<Person> where Person{Name, age, etc} .假设有一个List<Person> ,其中Person{Name, age, etc}

What I want is a ListBox with all Person's names as items.我想要的是一个 ListBox,其中包含所有 Person 的名称作为项目。 Only detail.只有细节。 I want it to update automatically.我希望它自动更新。

I wonder if it is possible to create a dynamic datasource that gets the names of the List<Person> and then the ListBox is binded to that datasource.我想知道是否可以创建一个动态数据源来获取List<Person>的名称,然后将ListBox绑定到该数据源。

Any suggestions other than using a datasourse are welcome.欢迎使用数据源以外的任何建议。 I found LinqDataSource that is used in .net 4. Anything similar to.Net3.5?我找到了.net 4中使用的LinqDataSource 。有什么类似于.Net3.5的吗?

I believe you are looking for something "more" than this but I am not sure from your question what that is.我相信您正在寻找比这“更多”的东西,但我不确定您的问题是什么。 So I am posting this code for you to further explain your goal.因此,我发布此代码以供您进一步解释您的目标。

    namespace SO_Forms_Demo
{
   public partial class Form1 : Form
   {
      List<person> people;
      public Form1()
      {
         InitializeComponent();

         List<string> dataList = new List<string>(){"Moe","Larry","Curly"};
         listBox1.DataSource = dataList;

          people = new List<person>(){new person(){name="Moe",age=44,shoeSize=9},
                                       new person(){name="Larry",age=45,shoeSize=10},
                                       new person(){name="Curly",age=46,shoeSize=11}
                                      };
          bindList2();
      }

      private void button1_Click(object sender, EventArgs e)
      {
         person Shemp = new person() { name = "Shemp", age = 49, shoeSize = 12 };
         people.Add(Shemp);
         bindList2();
      }

      private void bindList2()
      {
         listBox2.DataSource = null;
         listBox2.DisplayMember = "name";
         listBox2.DataSource = people;
      }

   }

   public class person
   {
      public string name { get; set; }
      public int age { get; set; }
      public int shoeSize { get; set; }
   }


}

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

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