System.ArgumentOutOfRangeException 在从网格视图更新数据表时发生
本文关键字:数据表 更新 视图 ArgumentOutOfRangeException 网格 System | 更新日期: 2023-09-27 18:31:08
我正在使用 Rowcommand 事件更新网格视图中的行以及数据表,但在将值分配给数据表中的行时发生异常。
protected void grduser_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
DataTable dt = (DataTable)ViewState["dtable"];
Int32 index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grduser.Rows[index];
// after this statement the exception occurs!
dt.Rows[row.DataItemIndex]["userid"] = ((TextBox)(row.Cells[0].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["username"] = ((TextBox)(row.Cells[1].FindControl("txtuname"))).Text;
dt.Rows[row.DataItemIndex]["usertype"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["email"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["salary"] = ((TextBox)(row.Cells[4].FindControl("txtsalary"))).Text;
grduser.EditIndex = -1;
ViewState["dtable"]=dt;
grduser.DataSource = (DataTable)(ViewState["dtable"]);
grduser.DataBind();
}
}
下面的网格视图源。
<asp:GridView ID="grduser" runat="server" AutoGenerateColumns="False"
onrowediting="grduser_RowEditing" onrowupdating="grduser_updateRow"
>
<Columns>
<asp:BoundField HeaderText="Id" DataField="userid"/>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtuname" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="User Type" DataField="usertype" />
<asp:BoundField HeaderText="Email" DataField="email" />
<asp:TemplateField HeaderText="Salary">
<EditItemTemplate>
<asp:TextBox ID="txtsalary" runat="server" Text='<%# Bind("salary") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("salary") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
你能试试这个吗?
protected void grduser_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
DataTable dt = (DataTable)ViewState["dtable"];
Int32 index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grduser.Rows[index];
dt.Rows[row.DataItemIndex]["userid"] = row.Cells[0].Text;
dt.Rows[row.DataItemIndex]["username"] = ((TextBox)(row.FindControl("txtuname"))).Text;
dt.Rows[row.DataItemIndex]["usertype"] = row.Cells[2].Text;
dt.Rows[row.DataItemIndex]["email"] = row.Cells[3].Text;
dt.Rows[row.DataItemIndex]["salary"] = ((TextBox)(row.FindControl("txtsalary"))).Text;
grduser.EditIndex = -1;
ViewState["dtable"]=dt;
grduser.DataSource = (DataTable)(ViewState["dtable"]);
grduser.DataBind();
}
}
您
收到该错误是因为您的e.CommandArgument
不是GridView
中的有效行号。例如,您的grduser
有 3 行,而e.CommandArgument
设置为 3。这将引发System.ArgumentOutOfRangeException
,因为grduser.Rows
是从 0 开始的,并且您很可能从 1 开始设置它。