RadGrid for ASP.NET

Binding To DataReader Send comments on this topic.
Populating the control with data > Binding To DataReader

Glossary Item Box

There are situations in which you may want to extract the values from data source in a DataReader instance (calling the ExecuteReader() method for your OleDbCommand/SqlCommand command). That DataReader can be used for Telerik RadGrid source - all you need to do is relate this instance with the DataSource property of the control.

In the code sample below we use Access data source and OleDbDataReader:

ASPX/ASCX Copy Code
<rad:radgrid id="RadGrid1" runat="server" AutoGenerateColumns="true" />

And in the code-behind:

C# Copy Code
 OleDbConnection conn = null;
 OleDbDataReader reader =
null;

 
private void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
 {
  RadGrid1.DataSource = ReadRecords(
"Select TOP 5 * FROM Customers", "Nwind.mdb");
 }

 
private OleDbDataReader ReadRecords(string query, string dbFile)
 {
  conn =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(dbFile));
  conn.Open();

  OleDbCommand cmd =
new OleDbCommand(query, conn);
  reader = cmd.ExecuteReader();

  
return reader;
 }

 
private void RadGrid1_DataBound(object sender, System.EventArgs e)
 {
  reader.Close();
  conn.Close();
 }
VB.NET Copy Code
Dim conn As OleDbConnection = Nothing
Dim reader As OleDbDataReader = Nothing

Private Sub RadGrid1_NeedDataSource([source] As Object, e As Telerik.WebControls.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
   RadGrid1.DataSource = ReadRecords("Select TOP 5 * FROM Customers", "Nwind.mdb")
End Sub 'RadGrid1_NeedDataSource


Private Function ReadRecords(query As String, dbFile As String) As OleDbDataReader
   conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(dbFile))
   conn.Open()

   Dim cmd As New OleDbCommand(query, conn)
   reader = cmd.ExecuteReader()

   Return reader
End Function 'ReadRecords


Private Sub RadGrid1_DataBound(sender As Object, e As System.EventArgs) Handles RadGrid.DataBound
   reader.Close()
   conn.Close()
End Sub 'RadGrid1_DataBound
 
Note: the most appropriate place to close the DataReader and the connection is in the DataBound event handler of the grid.