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…
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.?
By: Tejaswini on October 7, 2009
at 9:41 am