Question

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 image 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..

Was it helpful?

Solution

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.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top