Cast an image and change its source dynamically
I would like to change an images source based of a link in the database. I get an obect is not set to to a reference null message some on some of my pages. Here is the code that i am attempting to use to cast the image. It does work with the commented out code for all pages but about three...the only reason I think it breaks is because those pages use an inherited master page that the logo is located on. image.Src in the last part of the if statement, it does not have .Src avaliable. Is there any way to dynamically change an image source? Thank yo开发者_JS百科u!
if (row.ImageString != "")
{
//imgLogo.Src = "~" + row.ImageString;
Image image = new Image();
image.FindControl("imgLogo");
image.Src = "~" + row.ImageString;
}
I think you need something more like this:
Image image = row.FindControl("imgLogo");
image.ImageUrl = "~" + row.ImageString;
Your code is attempting to find an image in an image that you just initialized. You need to find the image in the row/item/parent container.
You are getting a Null reference because of the masterpage.
If you are using .Net 4.0 you need to set the ClientID to static on the image control.
If you are using .Net prior to 4.0 you need to look at the source code that is rendered when you build/run the page and find the image control and look at the ID of the control. Sometimes it will render as Content.ImageName or Content_ImageName....
Copy that into your image.Findcontrol method.
That'll fix ya up.
精彩评论