使用空数据集创建gridview时出现此错误。我想做的是在EmptyDataTemplate中填充一个下拉列表。从阅读其他文章来看,错误是由SqlConnection对象关闭后使用SqlDataReader绑定gridview引起的。但是,在gridview行填充后,行不会创建吗?
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.EmptyDataRow)
{
string connectionString3 = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
DropDownList ddl = (DropDownList)e.Row.FindControl("EOCEmpty");
using (SqlConnection conn3 = new SqlConnection(connectionString3))
{
SqlCommand cmd3 = new SqlCommand("SELECT DISTINCT GLAccountEOC, EOCDescription FROM Acct_GLAccount WHERE CostCenter = @CostCenter Order By EOCDescription", conn3);
cmd3.Parameters.Add("@CostCenter", System.Data.SqlDbType.Int);
cmd3.Parameters["@CostCenter"].Value = "3215";
try
{
conn3.Open();
SqlDataReader cmdreader3 = cmd3.ExecuteReader();
ddl.DataSource = cmdreader3;
ddl.DataValueField = "GLAccountEOC";
ddl.DataTextField = "EOCDescription";
ddl.DataBind();
cmdreader3.Close();
}
finally
{
conn3.Close();
}
}
}
}
答案 0 :(得分:1)
问题似乎出现在以下几行中:
SqlDataReader cmdreader3 = cmd3.ExecuteReader();
ddl.DataSource = cmdreader3;
您应该知道,ExecuteReader()
方法将构建SqlDataReader
实例(仅向前流),并且在尝试访问阅读器时似乎关闭了连接。考虑使用SqlDataReader.Read()
方法打开阅读器并前进至第一条记录,或将内容加载到内存DataSet
/ DataTable
中,并将其用作GridView的数据源。
以下是在SqlDataReader
内加载DataTable
内容的示例:
var dt = new DataTable();
using (SqlConnection conn3 = new SqlConnection(connectionString3))
{
SqlCommand cmd3 = new SqlCommand("SELECT DISTINCT GLAccountEOC, EOCDescription FROM Acct_GLAccount WHERE CostCenter = @CostCenter Order By EOCDescription", conn3);
cmd3.Parameters.Add("@CostCenter", System.Data.SqlDbType.Int);
cmd3.Parameters["@CostCenter"].Value = "3215";
try
{
conn3.Open();
SqlDataReader cmdreader3 = cmd3.ExecuteReader();
if (cmdreader3.HasRows)
{
dt.Load(cmdreader3);
ddl.DataSource = dt; // use DataTable instead of SqlDataReader
ddl.DataValueField = "GLAccountEOC";
ddl.DataTextField = "EOCDescription";
ddl.DataBind();
}
cmdreader3.Close();
}
finally
{
conn3.Close();
}
}
如果问题仍然存在,请使用RowDataBound
事件处理程序而不是RowCreated
来填充下拉列表值(请参见difference between RowCreated & RowDataBound event)。
类似的问题:
asp.net Invalid attempt to FieldCount when reader is closed error