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