Posted by: R Manimaran | October 17, 2007

Convert the DataReader output to DataTable in C#

Convert the DataReader output to DataTable in C#  

In this exampke I load a listbox from a DataTable. 

Loading part. 

try{SqlConnection connection=new SqlConnection(“Server=wkst9;database=projectServer;uid=sa;password=sa;”);

string Sql=”SELECT PROJ_ID, TASK_NAME FROM MSP_TASKS WHERE TASK_NAME<>””;

SqlCommand cmd=new SqlCommand(Sql,connection);Connection.Open();

SqlDataReader reader=cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); 

FillDT dra=new FillDT();

DataTable dt=new DataTable();

 dra.FillFromReader(dt,reader);

reader.Close();

 for(int i=0;i<dt.Rows.Count;i++)

{listBox1.Items.Add(dt.Rows [i][1].ToString());}

}

catch(Exception ex)

{MessageBox.Show(ex.Message);

}

FillDt is a Class file where I did actual filling of dataReader to DataTable. For that we need to inherit DbDataAdapter interface.

 public class FillDT:DbDataAdapter

 {/// <summary>

/// Use this Method to fill the DataTable from the DataReader/// </summary>/// <param name=”dataTable”></param>/// <param name=”dataReader”></param>/// <returns></returns>

public int FillFromReader(DataTable dataTable,IDataReader dataReader)

{     

 return this.Fill(dataTable,dataReader);

}

protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType,DataTableMapping tableMapping ){return null;}

protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping ){          return null;

 protected override void OnRowUpdated( RowUpdatedEventArgs value ){} protected override void OnRowUpdating( RowUpdatingEventArgs value){} 

As we inherit the Interface, we need to override the methods in the Interface.( CreateRowUpdatedEvent, CreateRowUpdatingEvent, OnRowUpdated, OnRowUpdating).

Happing Coding…

Advertisements

Responses

  1. Hi,
    I think by just writing…

    DataTable.Load Method (IDataReader)
    we can do this …

    No need to write class..

    and i didn’t get ..if u r using DataReader..why going for again DataAdapter…mixig of Connected and disconnected architecture.?

  2. Well done ! Very usefull !
    Thank you


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: