How to populate a DataGrid using a DataReader

Platform: ASP.NET| Category: DataGrid

<asp:DataGrid id='DataGrid1' runat='server'></asp:DataGrid>

Use Namespace System.Data.SqlClient

VB.NET


Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’Put user code to initialize the page here
Try
	cn = New SqlConnection('server=localhost;uid=sa;pwd=;database=northwind')
	cmd = New SqlCommand('select * from employees ', cn)
	cn.Open()
	rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
	DataGrid1.DataSource = rdr
	DataGrid1.DataBind()
Catch ex As Exception
	Response.Write(ex.Message.ToString())
Finally
	rdr.Close()
	cn.Close()
End Try
End Sub ’Page_Load 

C#


SqlConnection cn ;
SqlCommand cmd ;
SqlDataReader rdr ; 
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	try
	{
		cn = new SqlConnection('server=localhost;uid=sa;pwd=;database=northwind');
		cmd = new SqlCommand( 'select * from employees ', cn);
		cn.Open();
		rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
		DataGrid1.DataSource = rdr;
		DataGrid1.DataBind();
	}
	catch (Exception ex)
	{
		Response.Write (ex.Message.ToString ());
	}
	finally
	{
		rdr.Close();
		cn.Close();
	}
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.