0

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?

mogorilla
  • 195
  • 2
  • 13
  • so row["starts]" returns a 1? otherwise it wouldn't find it Do web controls allow names starting with a number when it comes to coding later? Wouldn't it be safer to be _tab_content_1 ? – BugFinder Jul 31 '15 at 14:00
  • @BugFinder I've changed it so it'll be tab_content_1 but still same error.. – mogorilla Jul 31 '15 at 14:26
  • Please include the aspx markup. I think we need that to see what's going wrong here. – Carl Bussema Jul 31 '15 at 14:33

1 Answers1

1

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
        }
    }
Carl Bussema
  • 1,684
  • 2
  • 17
  • 35