Thursday, June 7, 2012
Binding Generic List<> Class to the Gridview using DataReader or Datatable
Here now we will fetch the data of a table from Database and bind it to Gridview using ListClass.
First Create a Class
public class Buzz
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private string desc;
public string Desc
{
get { return desc; }
set { desc = value; }
}
}
public class BuzzList : List<Buzz>
{ }
In the above Class Buzz,it takes to members title and description.And also we can see another class BuzzList which is inherited from List<Buzz>
Now in the PageLoad
SqlConnection con = new SqlConnection("ur db connectionstring parameters");
SqlCommand cmd = new MySqlCommand("select * from BUZZ", con);
//BUZZ is the table in Database
con.Open();
try
{
BuzzList objBuzzList = new BuzzList();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Buzz objBuzz = new Buzz();
objBuzz.Title = dr["TITLE"].ToString();
//TITLE is the Column in BUZZ table
objBuzz.Desc = dr["DESCRIPTION"].ToString();
//DESCRIPTION is the Column in BUZZ table
objBuzzList.Add(objBuzz);
}
GridView1.DataSource = objBuzzList;
GridView1.DataBind();
}
First Create a Class
public class Buzz
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private string desc;
public string Desc
{
get { return desc; }
set { desc = value; }
}
}
public class BuzzList : List<Buzz>
{ }
In the above Class Buzz,it takes to members title and description.And also we can see another class BuzzList which is inherited from List<Buzz>
Now in the PageLoad
SqlConnection con = new SqlConnection("ur db connectionstring parameters");
SqlCommand cmd = new MySqlCommand("select * from BUZZ", con);
//BUZZ is the table in Database
con.Open();
try
{
BuzzList objBuzzList = new BuzzList();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Buzz objBuzz = new Buzz();
objBuzz.Title = dr["TITLE"].ToString();
//TITLE is the Column in BUZZ table
objBuzz.Desc = dr["DESCRIPTION"].ToString();
//DESCRIPTION is the Column in BUZZ table
objBuzzList.Add(objBuzz);
}
GridView1.DataSource = objBuzzList;
GridView1.DataBind();
}
Tuesday, June 5, 2012
Subscribe to:
Posts (Atom)