Tuesday, September 9, 2008

Bind Generic List To DataBound Control.

Suppose you have class called Person that represent person.
(This is specific to ASP.net 3.5 , C# 3.0)

public class Person
{
public Person()
{
this.Name = "";
this.Email = "";
}

public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
}

Generic feature available in .NET Framework 2.0 onwards. So you can use that to create generic list.

Here we create List of Person using following code.

System.Collections.Generic.List lst =
new System.Collections.Generic.List()
{
new Person{Name = "XYZ" , Email = "xyz@xyz.com"},
new Person{Name = "123" , Email = "123@xyz.com"}
};

Bind to GridView.

GridView1.DataSource = lst;
GridView.DataBind();


Bind To ListBox

Listbox1.DataSource = lst;
Listbox1.DataBind();

Binding with gridview works perfect and display Name and Email as column. Same is not happen with ListBox.

ListBox Display item something like

Person
Person But it not display anything.

For that you have to do following thing.

ListBox1.DataSource =lst;
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Email";
ListBox1.DataBind();

So It display name and ListBox1.SelectedValue contain appropiate Eamil Id.

No comments: