[求助]用SqlDataReader对DataGrid数据绑定无法取值的问题请教

birdxxxx 2003-06-18 08:45:46
我先写了一个简单的方法,
public class Customer
{
public SqlDataReader CustomerList()
{
SqlConnection myConnection = new SqlConnection("****");
SqlCommand myCommand = new SqlCommand("select CustID,CustName from b_Customers order by CustID", myConnection);

myConnection.Open();
SqlDataReader myDataReader = myCommand.ExecuteReader();
myConnection.Close();

return myDataReader;
}
}
然后我在页面的Page_Load事件中用一个DataGrid来绑定:
Customer myCustomer = new Customer();
dgList.DataSource = myCustomer.CustomerList();
dgList.DataBind();
但是系统报错,提示:
异常详细信息: System.InvalidOperationException: 阅读器关闭时 FieldCount 的尝试无效

我把myConnection.Close()这一行放到return myDataReader行后面,或者写成:
SqlDataReader mydataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
均不会出现问题。这是为什么?因为无论怎么myDataReader都已经得到数据了呀?

还有一个问题也想问一下:我看有的书上对于SqlDataReader值的返回方式是用result,但result在该方法中并未作任何定义。是书本中的问题,还是本来result就代表一定的含义呢?
...全文
18 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
birdxxxx 2003-06-18
  • 打赏
  • 举报
回复
谢谢思归兄。
saucer 2003-06-18
  • 打赏
  • 举报
回复
no, datareader is forward-only readonly stream, if you closed the connection, the connection in datareader is broken, change

SqlConnection myConnection = new SqlConnection("****");
SqlCommand myCommand = new SqlCommand("select CustID,CustName from b_Customers order by CustID", myConnection);
myConnection.Open();
SqlDataReader myDataReader = myCommand.ExecuteReader();
myConnection.Close();
return myDataReader;

====>
SqlConnection myConnection = new SqlConnection("****");
SqlCommand myCommand = new SqlCommand("select CustID,CustName from b_Customers order by CustID", myConnection);
myConnection.Open();
SqlDataReader myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
return myDataReader;


...
Customer myCustomer = new Customer();
SqlDataReader dataReader = myCustomer.CustomerList();
dgList.DataSource = dataReader;
dgList.DataBind();
dataReader.Close();

62,025

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧