Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

FindControl results in null reference

I have anchor tags like this

 <div id="menu_container">
            <ul id="nav-bar">
                <li><a href="Default.aspx" runat="server" id="menu_item_default">Home</a></li>
                <li><a href="Account.aspx" runat="server" id="menu_item_account" >Account</a></li>
                <li><a href="Servers.aspx" runat="server" id="menu_item_servers">Servers</a></li>
                <li><a href="Statistics.aspx" runat="server" id="menu_item_statistics">Statistics</a></li>
                <li><a href="Tutorials.aspx" runat="server" id="menu_item_tutorials">Tutorials</a></li>
                <li><a href="Contact.aspx" runat="server" id="menu_item_contact">Contact us</a></li>
                <div id="login_registration_container">
                    <a href="#" id="login">Sign in</a> / <a href="Registration.aspx" id="register">Register</a>
                </div>
            </ul>
        </div>

I want to change the CSS class for menu_item_default this way:

WebControl wc = (WebControl)FindControl("#menu_item_default");
wc.Attributes.Add("class", "value");

error: null reference exception

How can this be done?

Upvotes: 1

Views: 2949

Answers (3)

MatteKarla
MatteKarla

Reputation: 2737

Using a MasterPage and the element is in a ContentPlaceholder:

If so then you must retrieve the ContentPlaceholder first, and from it retrive the element you want.

If your page has the following Content-area for example:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

Then you would do the following (error handling omitted):

   var mainCtrl = Master.FindControl("MainContent");
   var anchor = (HtmlAnchor) mainCtrl.FindControl("menu_item_default");
   anchor.Attributes.Add("class", "value");

            

Using a MasterPage and the element is in the MasterPage:

use:

   var anchor = (HtmlAnchor) Master.FindControl("menu_item_default");

Upvotes: 3

Chris
Chris

Reputation: 370

Is there a particular reason you are using a regular anchor tag? Why not use an ASP.Net LinkButton? That will make it much easier to reference in the code.

If the control is on the master page, try Master.FindControl()

Upvotes: 0

Loki Kriasus
Loki Kriasus

Reputation: 1301

You shouldn't use '#' symbol in the FindControl argument:

WebControl wc = (WebControl)FindControl("menu_item_default");

Upvotes: 4

Related Questions