Simple question: DataTable & DataGrid

  • Thread starter Thread starter Doug
  • Start date Start date
D

Doug

Hi,

I'm trying to load data from SQL Server into a DataGrid. I planned on using
a DataTable to store the data, but I can't get the logic correct. Can
someone please tell me what I'm doing wrong? Thanks.

try

{

DatabaseConnection dc = new DatabaseConnection(); //this handles all the ADO
connections - this works fine used in other parts of the application

dc.Connect(); //opens the connection for reading

this.sqlSelectCommand1.CommandText = "SELECT RecipeIngredientName,
IngredientQuantity FROM RecipeIngredients WHERE (RecipeID = " + sRecipeID +
") order by RecipeIngredientName asc";


SqlCommand cmdSQL = null;


cmdSQL = new SqlCommand(this.sqlSelectCommand1.CommandText,dc.Connection);

SqlDataReader reader = cmdSQL.ExecuteReader();


while (reader.Read())

{

What do I do here? I need to load the data into a table so the grid can
display it

}



} //try



Thanks in advance,

Doug
 
If it's a web app, then all you need to do is can the While Dr.Read and then
use
MyDataGrid.DataSource = command.ExecuteReader
MyDataGrid.DataBind

If you are on the desktop, you can't do this iwth a reader so you'd just
declare a DataAdapter, set it's command property to your command object

SqlDataAdapter da = new SqlDataAdapter(myCommand);

Then declare either a DataSet or a DataTable and use DataAdapter fill

DataSet ds = new DataSet();

da.Fill(ds, "SometableName");

myDataGrid.DataSource = ds.Tables[0];
myDataGrid.DataBind;

(of course, you need to add your own exception logic here)

Remember that DataReaders work in a connected mode...they need an open
connection and walk through the resultset. DataTables grab all the data and
cache it locally. You can't move backward in a DataReader, only formward,
this isn't the case with a DataTable. The tradeoff is speed, but that's
beyond the scope of this post.

HTH,

Bill
 
Back
Top