开发者

how to access the dynamically created HTML control from code behind in asp.net

开发者 https://www.devze.com 2023-04-09 17:48 出处:网络
i have a webpage, wherein i am using a simple foreach loop and creating table structure, wherein i am displaying an image in td, the requirement is i want to access the imag开发者_如何学Goe created in

i have a webpage, wherein i am using a simple foreach loop and creating table structure, wherein i am displaying an image in td, the requirement is i want to access the imag开发者_如何学Goe created in td, from code-behind on page load.

but i am unable to find the control, i have made the control as runat='server' and also setted the id.

foreach (DataRow r in dtLogic.TopStories(Convert.ToInt32(ConfigurationManager.AppSettings["TopArticles"]), Convert.ToInt32(ConfigurationManager.AppSettings["PortalId"])).Rows)
        {
            i++;
            str.Append("<table cellpadding='0' cellspacing='0' class='newsItem'>");
            str.Append("<tr>");
            str.Append("<td><img runat='server' id='img"+i+"' class='thumb' src='" + GetAppSettingValue("MainSiteUrl") + "" + r["image"].ToString() + "' width='128' height='73'></td>");
            str.Append("<td><p class='newsTitle'><a href='" + r["URL"].ToString() + "'>" + r["title"].ToString() + "</a></p></td>");
            str.Append("<td><img class='arrow' src='/images/arrow.png'></td>");
            str.Append("</tr>");
            str.Append("</table>");
        }

now when i access this image from code behind like below..

HtmlImage img = (HtmlImage)this.FindControl("img1");

i gets the NullReference for the img object..

can anyone tell me why its not getting the image, which is runat='server' and rendering on the page..


You can't access it as it won't exist on postback. An image control isn't posted back to the server. If you have to bind events to it (for when its clicked on) you generally want to create the control in page_init and rebind its events to get the dynamic control to work.


Adam Tuliper is spot on.

Either store the value in a hidden textbox which gets posted back.

or

A way to do this is create using web server controls. (This is much harder work)

Image img = new image()....
HtmlTable tabl = new HtmlTable()
HtmlTr ...
HtmlTd ...
td.Controls.Add(img);

THen with dynamic controls, they must be created before viewstete is restored, so recreate these controls in overriden OnLoad event.

(BTW, you cant just add runat='server' as a string to anything. Check for yourself. View source on your webpage and you will see runat='server' in the source. Any other server control will not have the attribute in the view source).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号