GridView控件定义如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="ObjectDataSource1" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="Id">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" Visible="False" />
<asp:TemplateField HeaderText="Teacher">
<ItemTemplate>
<a href="../../../index.aspx?teacherId=<%#Eval("Teacher.Id") %>"><asp:Label ID="Label12" runat="server" Text='<%# Eval("Teacher.Account") %>'></asp:Label></a>
</ItemTemplate>
<asp:TemplateField HeaderText="Operation">
<ItemTemplate>
<asp:Button runat="server" Text="Agree" ID="btnAgree" CommandName="agree" >
<asp:Button runat="server" Text="Disagree" ID="btnDisagree" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
然后它的RowCommand函数如下:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);//int index = Convert.ToInt32(e.CommandArgument);
string id = this.GridView1.DataKeys[index].Value.ToString();
if (e.CommandName == "agree")
{
OrganizationResideApplyDso.UpdateStatus(id, ResideApplyStatus.Agreed);
GridView1.DataBind();
}
else if (e.CommandName == "disagree")
{
OrganizationResideApplyDso.UpdateStatus(id, ResideApplyStatus.None);
GridView1.DataBind();
}
}
但在第一行int index=Convert32....处老是出现错误,原来发现那个e.CommandArgument为空:""
现将GridView中的两个按钮修改如下就可以了(加上CommandArgument=" <%# Container.DataItemIndex % >" ):
<ItemTemplate>
<asp:Button runat="server" Text="Agree" ID="btnAgree" CommandName="agree" CommandArgument=" <%# Container.DataItemIndex % >" />
<asp:Button runat="server" Text="Disagree" ID="btnDisagree" CommandArgument=" <%# Container.DataItemIndex % >" />
</ItemTemplate>