如何查找网格视图按钮单击事件?

时间:2013-09-24 04:30:15

标签: asp.net c#-4.0

Button btnAddrecord = (Button)sender;
GridViewRow gvr =(GridViewRow)btnAddrecord.NamingContainer;
if (btnAddrecord.CommandName == "onAddMaterial")

3 个答案:

答案 0 :(得分:4)

在网格视图标记中定义按钮,并为按钮分配CommandName值,如下所示:

<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server"  
        OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="Add Record">
            <ItemTemplate>
                <asp:Button ID="btnAddRecord"  
                            CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" 
                            CommandName="AddRecord" runat="server" Text="Add" />
            </ItemTemplate>
        </asp:TemplateField> 
    </Columns>
</asp:GridView>

现在在您的代码隐藏中,您可以处理OnRowCommand事件和AddRecord命令,如下所示:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "AddRecord")
    {
        // Get index of row passed as command argument
        int index = Convert.ToInt32(e.CommandArgument.ToString());

        // Your logic here
    }
}

答案 1 :(得分:0)

1.给出按钮的命令名称。
2.然后在gridview内部

if e.commandname="yourcommandname"
{
//your code..
}

答案 2 :(得分:0)

     <!--We use onrowcommand for getting the selected row -->
<asp:GridView runat="server" ID="gvTest"  AutoGenerateColumns="False"  OnRowCommand="gvTest_OnRowCommand" >
             <Columns>
                <asp:TemplateField HeaderText="BookId" >
               <ItemTemplate>
                   <asp:Label runat="server" ID="lblBookId" Text='<%# Bind("[BookId]") %>'></asp:Label>
               </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox runat="server" ID="txtBookId" Text='<%# Bind("[BookId]") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
             </Columns>
            </asp:TemplateField>
                <asp:TemplateField HeaderText="Options">
                    <ItemTemplate>
                      <asp:Button runat="server" ID="btnDelete"  CommandArgument="<%# Container.DisplayIndex %>" CommandName="IsDelete" Text="Delete"></asp:Button>
                    </ItemTemplate>
                </asp:TemplateField>

 //Code Behind

 protected void gvTest_OnRowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            //getting rowindex which we have selected by using CommandArgument

                int rowindex = Convert.ToInt32(e.CommandArgument);


                    if (e.CommandName == "IsDelete")
                    {

                        int bkid = gvTest.Rows[rowindex].Cells[0].FindControl("BookId");

                        //call a method to delete book using the bkid 

                    }

        }
        catch (Exception ex)
        {

            Response.Write(ex);
        }
    }