Mikhail Galushin Mikhail Galushin - 2 months ago 15
ASP.NET (C#) Question

How can I get access to the button from code behind

How can I get access to the button from code behind using id "btnAutocomplete"?

<asp:GridView DataKeyNames="AutocompleteSchoolChild_Child" Width="1500px" CssClass="table table-bordered" OnDataBound="GridAutocomplete_OnDataBound"
ID="GridAutocomplete" runat="server" AutoGenerateColumns="false" AllowPaging="true" DataSourceID="sqlAutocomplete" Visible="true" PageSize="10"
OnSelectedIndexChanged="GridAutocomplete_OnSelectedIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-width="80px">
<ItemTemplate runat="server">
<asp:Button CssClass="btn btn-default" runat="server" ID="btnAutocomplete" Text="Зачислить" CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
...

Answer Source

I assume that you want to change button text in currently selected row, so that you need to use FindControl with GridViewRow instance & cast it to a Button control:

protected void GridAutocomplete_OnSelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = GridAutocomplete.SelectedRow;
    Button btnAutocomplete = (Button)row.FindControl("btnAutocomplete");

    btnAutocomplete.Text = "Insert"; // example to use button property
}

If you want to change button text in all GridView rows, you can use foreach loop together with GridViewRow instances on the same event handler:

foreach (GridViewRow row in GridAutocomplete.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        Button btnAutocomplete = (Button)row.FindControl("btnAutocomplete");
        btnAutocomplete.Text = "Insert"; // example to use button text property
    }
}

If you're not sure that FindControl cast works properly, change all direct casts to as operator & use null checking like this:

GridViewRow row = (sender as GridView).NamingContainer as GridViewRow;
Button btnAutocomplete = row.FindControl("btnAutocomplete") as Button;
if (btnAutocomplete != null)
{
    btnAutocomplete.Text = "Insert"; // example to use button text property
}

NB: The goal here is getting GridViewRow instance first before accessing button control inside TemplateField, so that SelectedRow is a proper way to get currently selected row.