C# 无法将SqlDataReader加载到表中

C# 无法将SqlDataReader加载到表中,c#,sql,sql-server,C#,Sql,Sql Server,我有一个来自SQL Server命令的SqlDataReader,我想在DataDridView中显示以下代码: SqlDataReader dr=product.RetriveDetailsOfOneProduct(); DataTable dt = new DataTable(); dt.Load(dr); DataGrid.DataSource = dr; 我使用断点检查它,我的SqlDataReader有行,但当加载到DataTable时,它是空的(没有行) 我怎样才能解决这个问题 它

我有一个来自SQL Server命令的
SqlDataReader
,我想在
DataDridView
中显示以下代码:

SqlDataReader dr=product.RetriveDetailsOfOneProduct();
DataTable dt = new DataTable();
dt.Load(dr);
DataGrid.DataSource = dr;
我使用断点检查它,我的
SqlDataReader
有行,但当加载到
DataTable
时,它是空的(没有行)

我怎样才能解决这个问题

它是my DataAccess类的函数,其中返回
SqlDataReader

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());
}

分配datatable,而不是datareader

DataGrid.DataSource = dt;

分配datatable,而不是datareader

DataGrid.DataSource = dt;

您的问题是将数据源设置为数据读取器而不是数据表

DataGrid.DataSource = dr;
应该是

DataGrid.DataSource = dt;
DataGrid.DataBind();

您的问题是将数据源设置为数据读取器而不是数据表

DataGrid.DataSource = dr;
应该是

DataGrid.DataSource = dt;
DataGrid.DataBind();

您还需要确保将数据绑定到DataGrid,只是设置源代码并不好。我建议将查询也移植到存储过程。与在代码中编辑动态sql相比,维护动态sql更容易。另外,使用(){}将SqlCommand对象包装成一个
,用于自动处理感谢大家的努力。我在将dt分配给DataGrid时犯了一个错误,现在它工作正常请选择一个答案作为可接受的答案谢谢这两个答案都是相同的和可接受的你需要确保你将数据绑定到DataGrid以及只是设置源不好我建议将查询也移植到存储过程。与在代码中编辑动态sql相比,维护动态sql更容易。另外,使用(){}
将SqlCommand对象包装成一个
,用于自动处理感谢大家的努力。我在将dt分配给DataGrid时犯了一个错误,现在效果很好。请选择一个答案作为可接受的答案,谢谢。这两个答案都是相同且可接受的