如何从GridView中的按钮调用函数?

时间:2011-06-15 13:05:30

标签: asp.net webforms

我的页面上有一个GridView,此视图的单列由按钮组成。单击这些按钮,我想要一个方法被调用,它位于页面后面的代码中。我试过,OnClick按钮和GridView的OnRowCommand。但是,我仍然无法从代码页面后面调用该函数。

这是我的GridView。

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
    CssClass="formx2" AutoGenerateColumns="False" DataKeyNames="companyName"  >
    <Columns>
        <asp:TemplateField HeaderText="Düzenle" SortExpression="companyName" 
            HeaderStyle-CssClass="colDept">      
            <ItemTemplate>
                <asp:Button runat="server" ID="IncreaseButton" Text="Düzenle" 
                    CommandName="Select" CommandArgument="something" 
                    CssClass="accordionHeader" BorderColor ="White" 
                    Onclick="redirect"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

我的代码背后的方法,

protected void redirect(object sender, EventArgs e)
{
    TextBox1.Text = "test";
}

非常感谢帮助,我真的陷入了困境。

提前致谢。

1 个答案:

答案 0 :(得分:2)

像这样的东西

<asp:TemplateField HeaderText="Düzenle" SortExpression="companyName" HeaderStyle-CssClass="colDept">
 <ItemTemplate>
   <asp:Button ID="IncreaseButton" runat="server" 
    CommandName="Select" 
    CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
     />
 </ItemTemplate> 
</asp:TemplateField>

然后编码

Protected Sub GridView1_RowCommand(ByVal sender As Object, _
  ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
  If (e.CommandName = "Select") Then
    // Retrieve the row index stored in the CommandArgument property.
    Dim index As Integer = Convert.ToInt32(e.CommandArgument)

    // Retrieve the row that contains the button 

    Dim row As GridViewRow = GridView1.Rows(index)

    // Add code here 
  End If
 End Sub