0

I have a SqlDataReader from a SQL Server command and want I to show in a DataDridView with this code:

SqlDataReader dr=product.RetriveDetailsOfOneProduct();
DataTable dt = new DataTable();
dt.Load(dr);
DataGrid.DataSource = dr;

I checked it using breakpoints that my SqlDataReader has rows but when loading it into DataTable, it is empty (with no rows)

How can I fix this?

And it is function of my DataAccess class where SqlDataReader is returned:

internal SqlDataReader RetriveDetailsOfOneProduct(product product)
{
     string RetriveQuery = string.Format("SElect person.F_Name as N'Name ',person.L_Name as N'LastName',borrow.Person_Identity as N'Identity',borrow.T_Date as 'Date1', borrow.B_Date as 'Date2' from BorrowTable borrow Inner join PersonTable person on borrow.Product_Name=N'{0}' and person.Person_identity=borrow.Person_Identity ", product.Productname);

     SqlCommand cmd = new SqlCommand(RetriveQuery, conn);
     // conn.Close();  //if i close the Connection(conn) it runs into error
     return(cmd.ExecuteReader());
}
8
  • you need to make sure you bind the data to the DataGrid as well just setting the Source is not good enough Commented Feb 4, 2015 at 20:23
  • 1
    I would suggest porting the query over to a stored procedure as well. it will be easier to maintain vs trying to edit dynamic sql in your code. also wrap your SqlCommand Objects around a using(){} for auto disposing Commented Feb 4, 2015 at 20:30
  • thanks for all of you worked good.i made a mistake with assigning dt to DataGrid,now it works good Commented Feb 4, 2015 at 20:32
  • please select one of the answers as the acceptable answer thanks Commented Feb 4, 2015 at 20:33
  • both of them are the same and acceptable Commented Feb 4, 2015 at 20:34

2 Answers 2

3

Your issue is that you are setting the data source to the data reader instead of the data table.

DataGrid.DataSource = dr;

should be

DataGrid.DataSource = dt;
DataGrid.DataBind();
Sign up to request clarification or add additional context in comments.

Comments

2

Assign the datatable, not the datareader...

DataGrid.DataSource = dt;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.