1

Basically I have a GridView:

        <asp:GridView ID="gvServices" runat="server" CellPadding="4" 
                      ForeColor="#333333" GridLines="None" AllowSorting="True" 
                      AutoGenerateColumns="False" OnRowCommand="gvServices_RowCommand">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

And inside I have 2 TemplateFields:

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="btnStart" runat="server" Text="Start" CommandName="StartService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="btnStop" runat="server" Text="Stop" CommandName="StopService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
                    </ItemTemplate>
                </asp:TemplateField>

Finally I have the method thats supposed to fire when clicking on either of the Buttons on the gridView, problem is that when I click either of them the event does not get called at all

    public void gvServices_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "StartService")
        {
            StartServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
        }
        if (e.CommandName == "StopService")
        {
            StopServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
        }
        loadGridView();
    }
4

2 回答 2

5

GridView 上的 RowCommand 确实从 TemplateField 中的按钮触发。查看此线程的答案:

网格视图中的链接按钮未触发

于 2012-11-28T19:38:53.217 回答
4

你需要听按钮RowCommandGridView.RowCommandasp:ButtonField在每一行都有一个时使用。

ASP代码:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="btnStart" runat="server" Text="Start" OnCommand="GridButtons_Command" CommandName="StartService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="btnStop" runat="server" Text="Stop" OnCommand="GridButtons_Command" CommandName="StopService" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
    </ItemTemplate>
</asp:TemplateField>

代码背后:

public void GridButtons_Command(object sender, CommandEventArgs e)
{
    int index = Convert.ToInt32(e.CommandArgument);
    if (e.CommandName == "StartService")
    {
        StartServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
    }
    if (e.CommandName == "StopService")
    {
        StopServiceItem(gvServices.Rows[index].Cells[0].Text, locations[index]);
    }
    loadGridView();
}
于 2012-08-10T14:38:43.150 回答