GridView RowCreated:关闭阅读器时尝试调用FieldCount无效

时间:2019-01-02 17:22:14

标签: c# asp.net

使用空数据集创建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();
            }
        }
    }
}

1 个答案:

答案 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