How Do I Bind Datagrid with SqlDataReader in C#
By October 29, 2005
This article will show, how do we bind our binding controls like DataGrid, DataList using SqlDataReader.
This class will request to a database class to return SqlDataReader to Bind DataGrid Control.
using System;
using System.Data.SqlClient;
using System.Web;
Class BindGrid : System.Web.UI.Page
{
private Returneader returnReader;
private DataGrid dataGrid;
public BindGrid()
{returnReader = new ReturnReader();
BindDataGrid();}
Private void BindDataGrid()
{dataGrid.DataSource = returnReader.CreateReader();
dataGrid.DataBind();}
}
Class ReturnReader
{
private SqlDataReader sqlDataReader = null;
public SqlDataReader CreateReader()
{SqlConnection con = new SqlConnection("SERVER=.;UID=Ashish;PWD=Ashish;DATABASE =NorthWind");
SqlCommand objCommand = new SqlCommand("SELECT FirstName, LAstName from Employees", con);
sqlDataReader = objCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return sqlDataReader;}