简体   繁体   中英

FindControl throwing null exception

I am trying to dynamically create a div within the tab_content which is also a div.. then I am trying to check if the current row + "_tab_content" is equal to any ID within the tab_content, if so then do something.

For example the row["stars"].ToString() will print out "1" which makes it "1_tab_content"

int i = 1;
tab_content.Controls.Add(new LiteralControl("<div class='tab-pane' id='" + i.ToString() + "_tab_content' </div>"));

        foreach(DataRow row in gymsByStars.Rows)
        {   
            if(row["stars"].ToString() + "_tab_content" == tab_content.FindControl(row["stars"].ToString() + "_tab_content").ID.ToString())
            {
               // Do Something
            }
        }

However for some reason I recieve this error on the IF statement line System.NullReferenceException: Object reference not set to an instance of an object. I honestly don't understand why though because the control has been dynamically created?

Does anyone understand what I am doing wrong?

FindControl can only find controls where runat="server" is set. You may want to consider adding a Panel instead of a LiteralControl .

It looks like you're trying to find the <div> that you're creating with new LiteralControl(). In additional to this being a bad idea (create a Panel instead), it's not going to work because that div does not have a runat=server tag when you create it. Even then I'm not sure if it would really work, you shouldn't normally create generic HTML tags with runat=server in a code-behind.

var pnl = new Panel() { CssClass = "tab-pane", ID = i.ToString() + "_tab_content" };
tab_content.Controls.Add(pnl);

    foreach(DataRow row in gymsByStars.Rows)
    {   
        if(row["stars"].ToString() + "_tab_content" == tab_content.FindControl(row["stars"].ToString() + "_tab_content").ID.ToString())
        {
           // Do Something
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM