Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find div at run time at server side in c#

Tags:

html

c#

asp.net

Hye all.

i have div in index.aspx page like this

<div id="MainDiv" runat="server">

and i am creating div from server side(At run time) like

 for (Int32 i = 0; i < 4; i++)
    {

        //Create here divFinal
        HtmlGenericControl divFinal = new HtmlGenericControl("div");
        divFinal.ID = i.ToString();

        divFinal.Attributes.Add("class", "column");


        mainDiv.Controls.Add(divFinal);
        //add to maindiv


        HtmlGenericControl div = new HtmlGenericControl("div");
        div.ID = "t_e_" + i.ToString() + "_a";
        div.Style["background-color"] = "#CFD8E6";
        div.Attributes.Add("class", "grid");
        div.Attributes.Add("onclick", "OnMouseDownDiv(this)");

        div.Attributes.Add("onmouseover", "OnMouseDown(this)");
        div.Attributes.Add("onmouseout", "OnMouseUp(this)");
        divFinal.Controls.Add(div);

        // add to dvfinal


    }

After gen rate its look like this in HTML form

 <div id="mainDiv"><div id="0" class="column"><div id="t_e_0_a"></div></div><div id="1" class="column"><div id="t_e_1_a"></div></div></div>

Now I need to find div id t_e_0_a inside main Divdiv.

HtmlGenericControl div = 
    ((HtmlGenericControl)showdiv.FindControl("0")); 

But its give me error....

like image 951
Ankur Monga Avatar asked Oct 22 '22 21:10

Ankur Monga


1 Answers

You can't do it like you want as it is not a control. You should place runat="server" attribute on it, or you can get it somehow from showdiv.InnerHtml - there it should be presented as a string which you can parse with some HTML parser for .net (for instance, HTMLAgilityPack suggested here)

To create server side controls at run time, you can use something like below:

for (Int32 i = 0; i < 2; i++)
{
        HtmlGenericControl div = new HtmlGenericControl("div");
        div.ID = i.ToString();
        div.InnerHtml = i.ToString();
        div.ClientIDMode = ClientIDMode.Static; //this is for .NET 4.5 only. Required to have ClientID the same as ID.
        showdiv.Controls.Add(div);
}

and than, after controls are added, you should be able to use something like this:

HtmlGenericControl div=((HtmlGenericControl)showdiv.FindControl("1"))

to get those controls. But please remember that controls added like that, must be added for each request.

like image 119
Viktor S. Avatar answered Oct 24 '22 13:10

Viktor S.