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....
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With