[求助]用SqlDataReader对DataGrid数据绑定无法取值的问题请教
我先写了一个简单的方法,
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就代表一定的含义呢?