C# Gridview绑定错误索引1中的DropDownList为负或高于行计数
我一直在尝试绑定GridView的C# Gridview绑定错误索引1中的DropDownList为负或高于行计数,c#,asp.net,gridview,data-binding,drop-down-menu,C#,Asp.net,Gridview,Data Binding,Drop Down Menu,我一直在尝试绑定GridView的itemtemplate中的下拉列表。 但它给了我上面所说的错误“索引1要么为负,要么高于行数。” 我的GridView包含约100行,我想用特定数据绑定每个下拉列表。错误发生在onRowDataBoundEvent处,异常(由调试工具)在GridBinding方法处输出,以将GridView与主数据绑定 代码如下: if (e.Row.RowType == DataControlRowType.DataRow) { t
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
方法
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;
在代码中,您使用了许多类级对象。这些对象可以为空,也可以关闭连接等。在处理数据库时,最好特别使用方法级对象。可以重用连接字符串,如常量 为了澄清第一次传递到rowdataboundevent后发生的错误,100行的gridview在异常后只显示一个datarow。哪行代码引发了该错误?我发现错误e.row.rowindex等于grd.rows.count(应该是count-1)但是我不明白为什么会发生这种情况。另外,如果你在注释中加入if(_-ddtpcs!=null){--code-->}部分,那么就不会发生错误,代码工作正常……哪一行代码会抛出错误?谢谢,现在它工作得像个符咒:),请你解释一下我的错误,这样我就可以把它标记为一个答案。谢谢@Damith@Alok补充说明。还有一件事。。您可以对一次性对象使用
和块。因此,不需要通过代码关闭连接。感谢我用代码重新检查了您的解决方案,datatable对象在调用时为空。再次感谢
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;