Page. FindControl returns null for DIV

I have a page on which I create dynamiclly div controls and automatically number them.

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 as follows:

HtmlGenericControl div;

div = (HtmlGenericControl)Page.FindControl("picker" + e.CommandArgument.ToString());

string colorCode = div.Style["background-color"].ToString();

after this line of code, I get a ref ref null error. div is null. I tried HtmlControl and LiteralControl as an object type, and that doesn't help either.

Thank!

+3
source share
4 answers

Page.FindControl only works for server controls. You assign an identifier for the text in a literal control, which is a div, but not the control itself. If you set the ID of the control, you can find it, but I don’t know what you intend.

HTML. , runat = , ASP.NET , . - , , Page.FindControl . "declarepanel" aspx. ClientIdMode.Static , ASP.NET (, "MainContent_childPanel" )

<asp:Panel ID="declaredPanel" runat="server" ClientIDMode="Static" />

Page_Load:

    Panel p = new Panel();
    p.Style["background-color"] = "#aaeeaa";
    p.ID = "childPanel";
    p.ClientIDMode = System.Web.UI.ClientIDMode.Static;
    p.Controls.Add(new LiteralControl("<div id=\"div111\" runat=\"server\">Hello, world!</div>"));
    declaredPanel.Controls.Add(p);
    Panel p2 = declaredPanel.FindControl("childPanel") as Panel;
    string colorCode = p2.Style["background-color"]; // reports "#aaeeaa"

:

<div id="declaredPanel">
    <div id="childPanel" style="background-color:#aaeeaa;">
        <div id="div111" runat="server">Hello, world!</div>
    </div>
</div>
+4

OnInit . - : ASP.NET Visual #.NET

. -, OnInit, Page_Load. .

0

LiteralControl. DIV FindControl ID. div, "" LiteralControl. Control.FindControl NamingContainer (runat=server) ID. , FindControl (, ).

Look here ... The best way to find a control in ASP.NET

0
source

Try the following:

LiteralControl literalControl = new LiteralControl();
literalControl.ID = "divLiteralControl";
literalControl.Text = ...
subCell.Controls.Add(literalControl);

Then use the FindControl method to get the literal control and edit its text.

LiteralControl literalControl = 
    (LiteralControl) subCell.FindControl("divLiteralControl");
literalControl.Text = ...
0
source

All Articles