Farzad Salehi
Farzad Salehi

Reputation: 29

Can I access objects (button or hyperlink) within a templatefield in a Gridview?

I want to access an object (hyperlink or button) within a templatefield in a gridview. How do I do this?

Upvotes: 1

Views: 1094

Answers (2)

CAbbott
CAbbott

Reputation: 8098

Assuming that you're binding data to it, you'll want to look at doing that inside the RowDataBound event.

Here's an example of how to retrieve a control within a Template Field:

.aspx:

<asp:GridView ID="GridView1" Runat="server" 
    OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Template Field">
            <ItemTemplate>
                <asp:Button ID="btnTest" Runat="server" /> 
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code-behind:

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button btnTest = (Button)e.Row.FindControl("btnTest");
        btnTest.Text = "I'm in a Template Field";
    }
}

Upvotes: 1

Zo Has
Zo Has

Reputation: 13038

You can use it on RowDataBound or click event of your template control like

TextBox txtTemp= (TextBox )e.Row[e.RowIndex].FindControl("yourControlName");
string someText=txtTemp.Text;

Upvotes: 0

Related Questions