Z5 Concepts

C# - ASP.NET - Use FindControl on TemplateField ItemTemplate


by on 11. March 2011 20:46

Say for instance you have a

 

<asp:HyperLink ID="HyperLink1" runat="server" Text="Hyperlink"></asp:HyperLink>

 

 control on in you TemplateField ItemTemplate of a GridView control, and you need to some how modify the NavigateURL property of that control. You can utilize the FindControl function of the Gridview as so:

 

protected void Page_Load(object sender, EventArgs e)

{

 

    String NavigateURL =

   ((HyperLink)NameOfYourGridView1.FindControl("HyperLink1")).NavigateUrl;

 

}

 

If you try and use this on Page_Load or even in the GridView1_OnDataBound event, you will more than likely get Object reference not set to an instance of an object error. The key in using this properly is going to be in the OnRowDataBound event.

See, every row has the HyperLink control on it and how does it know which HyperLink to find in the GridView for modification purposes? It doesn't. So we must call this in the OnRowDataBound event as so:

 

 

    protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)

 

    {

 

      if ((e.Row.FindControl("HyperLink1") != null))

      {         

          //this demonstrates how to append a string to a hyperlink or url using

 StringBuilder class

          StringBuilder url = new StringBuilder();         

          url.Append((HyperLink)e.Row.FindControl("HyperLink1")).NavigateURL);

      }

    }

 

 

If you have any questions or problems, feel free to e-mail me at DJ@z5concepts.com

 

www.z5concepts.com

 

Tags:

C#.NET | Visual Studio 2008 | Websites

Comments are closed


Theme by Z5 Concepts