I have a page where I create div controls dynamiclly and number them automaticlly.
subCell = new TableCell();
subCell.Controls.Add(new LiteralControl(
"<div id=\"picker" + Index.ToString() + "\" runat=\"server\"
class=\"colorSelector\"><div style=\"background-color: #000000;\">Text
</div></div>"));
subRow.Cells.Add(subCell);
subTb.Rows.Add(subRow);
Later in the code I want to get the background-color value like so:
HtmlGenericControl div;
div = (HtmlGenericControl)Page.FindControl("picker" + e.CommandArgument.ToString());
string colorCode = div.Style["background-color"].ToString();
after these line of code I get a null object ref error.
div is null.
I have tried HtmlControl and LiteralControl as the object type and that does not help either.
Thank you!
Page.FindControl only works for server controls. You are assigning an id to text within the literal control which happens to be a div, but not the control itself. If you set the id of the control you should be able to find it, but I don’t know if that’s what you’re intending.
In response to your comment, check your HTML. The runat=server will probably be there because ASP.NET isn’t processing it as a control, it is treating it as content. Try something like this, noting that Page.FindControl only works on immediate children. Here I’ve declared a server panel named ‘declaredPanel’ in the aspx. ClientIdMode.Static makes it so ASP.NET won’t add parent names to the control (like “MainContent_childPanel”)
In Page_Load:
Produces this: