Gridview中的下拉列表绑定错误索引1为负或大于行数

本文关键字:大于 索引 下拉列表 绑定 错误 Gridview | 更新日期: 2023-09-27 18:11:38

我一直在尝试绑定一个下拉列表,这是存在于我的GridView的itemtemplate。但它给了我上面说的错误"索引1是负的或高于行数。"

我的GridView包含~100行,我想绑定每个下拉列表与特定的数据。错误发生在onRowDataBoundEvent和一个异常(由调试工具)是输出在GridBinding方法绑定GridView与主数据。

代码如下:

 if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
                DropDownList _ddtpcs = (DropDownList)e.Row.Cells[4].FindControl("_ddtsttpc");
                if (_ddtstsubs.SelectedIndex != 0 && _ddtstsubs.SelectedIndex != -1)
                {
                    if (_ddtpcs != null)
                    {
                        _ddtpcs.DataSource = _adl.LoadTopics(long.Parse(_ddtstsubs.SelectedValue));
                           _ddtpcs.DataTextField = "top_nm";
                           _ddtpcs.DataValueField = "top_id";
                           _ddtpcs.DataBind();
                           _ddtpcs.Items.Insert(0, new ListItem("Select", "0"));
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", POPUPBuilder.ShowPopUpMsg(ex.ToString()), true);
            }
        }

下面是gridbinding的代码:

 _grdqans.DataSource = _adl.LoadQans(long.Parse(_hdntstId.Value));
                _grdqans.DataBind();

GridView中的下拉列表为:

 <ItemTemplate>
        <asp:DropDownList ID="_ddtsttpc" runat="server">
    </asp:DropDownList>
</ItemTemplate>

LoadTopics方法

 internal object LoadTopics(long _subId)
    {
        try
        {
            cmd = new SqlCommand("sp_LoadTopics", con.getconnection());
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@subId", _subId);
            da = new SqlDataAdapter(cmd);
            dt.Clear();
            da.Fill(dt);
            cmd.Parameters.Clear();
            cmd.Connection.Close();
            cmd.Dispose();
            //da.Dispose();
            return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.closeconnection();
        }
    }

我在这里做错了什么?

Gridview中的下拉列表绑定错误索引1为负或大于行数

用下面的代码更新LoadTopics方法

DataTable topicDt = new DataTable();
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand("sp_LoadTopics",con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@subId", _subId);
    con.Open();
    using(SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
        da.Fill(topicDt);
    }
}
return topicDt;

在你的代码中,你使用了许多类级对象。这些对象可以为空或连接等可以关闭。最好使用方法级对象,特别是在使用数据库时。您可以像重用常量一样重用连接字符串。