【发布时间】:2015-01-16 13:39:16
【问题描述】:
我正在使用 Rowcommand 事件更新网格视图中的行以及 DataTable,但是在将值分配给 DataTable 中的行时发生异常。
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>
【问题讨论】:
-
注释行正下方的行
-
可能在这里
GridViewRow row = grduser.Rows[index] -
不,它发生在下一行
-
检查这个
((TextBox)(row.Cells[0].Controls[0])).Text是否提供了一些东西?row.DataItemIndex这也是,它给了什么? -
@yogi 是的,这句话有问题:**粗体((TextBox)(row.Cells[0].Controls[0])).Text**,它抛出异常。当我早些时候在 Row_updating 中检查它时它正在工作,但现在当我在 Row_command 中使用它时
标签: c# asp.net exception gridview datatable