单击TemplateField中的按钮时,RowCommand不会触发

时间:2012-08-10 14:34:59

标签: asp.net

基本上我有一个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" />

在里面我有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>

最后我有点击gridView上的任何一个按钮时应该触发的方法,问题是当我点击其中任何一个时,事件根本不会被调用

    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();
    }

2 个答案:

答案 0 :(得分:5)

GridView中的RowCommand从TemplateField中的按钮触发。看看这个主题的答案:

Linkbutton inside a gridview not firing

答案 1 :(得分:4)

您需要聆听RowCommand按钮。如果每行asp:ButtonField,则使用GridView.RowCommand

Aspx代码:

<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();
}