How to assign a data source to a general collection of lists?

I have a general list i.e. List<myclass> . Here myclass contains two string properties.

How to assign a list collection data source?

+6
source share
6 answers

Mirmal, I think English is not your first language, this question is not very clear. I think that what you are asking for is a list of your class, how you then bind this list to something (list or combobox, etc.).

Here is a simple piece of code on how to do this ...

 private void button2_Click(object sender, EventArgs e) { List<MyClass> list = new List<MyClass>(); list.Add(new MyClass() { FirstName = "Tim", Lastname = "Jarvis"}); list.Add(new MyClass() { FirstName = "John", Lastname = "Doe" }); listBox1.DataSource = list; listBox1.DisplayMember = "FirstName"; // or override MyClass ToString() method. } 

I hope this answers your question.

+11
source share

Start with a simple class:

  // create a dummy class public class MyClass { private string name; public MyClass(string name) { ItemName = name; } public string ItemName { get { return name; } set { name = value; } } } 

Create a binding list and add some classes to the list:

  // create a binding list BindingList<MyClass> my_list = new BindingList<MyClass>(); // add some clssses to the list my_list.Add(new MyClass("Item #1")); my_list.Add(new MyClass("Item #2")); 

Bind a list to a list data source indicating which class property should be used in the list display:

  // make the list the datasource for a listbox listBox1.DataSource = my_list; // this is the property of the class displayed in the listbox listBox1.DisplayMember = "ItemName"; 
+4
source share

You can transfer your list to the binding list:

 System.ComponentModel.BindingList<myClass> bindingList = new System.ComponentModel.BindingList<myClass>(originalList); 

Goran

+2
source share

You can not. This is because List is not an IBindableComponent. Windows Forms: See the MSDN Management Class .

+1
source share

You do not assign a data source to a List<> object. You can use List<> as a data source to control the user interface.

If you want you can get from List<> and implement IBindableComponent , which will allow you to provide mechanisms for binding data to the list. This is almost certainly not the best way to achieve what you want to do, though.

Edit: If you have a control and want to get a data source, and you know it as a List<> object, which you can simply do:

 List<MyClass> lst = listBox1.DataSource as List<MyClass>; 
+1
source share

You have the opposite. Data objects, such as grids, etc., can set up shared lists as a data source.

You must either manually fill out your list, or use a technology that populates it for you (e.g. LINQ to SQL, NHibernate)

0
source share

All Articles