简体   繁体   中英

How do I show and position an Image initialized in the codebehind on my page?

I have created a simple method to check if an image has been approved and finally returns it as an control. But how do i call and show it on the page? I've tried something like this in the aspx-file:

<% SendImage("DKBygMiniLogo.gif", "True"); %>

Here is the simple method:

protected Image SendImage(object Image, object Approved)
{
  bool approved = Convert.ToBoolean(Approved);
  Image img = new Image();
  if (approved)
  {
      img.ImageUrl = "~/images/Ads/" + Image.ToString();
      img.Visible = true;
  }
  else
  {
      img.ImageUrl = "~/images/Ads/" + Image.ToString();
      img.Visible = false;
  }
   return img;
}

How do I actually show the image?

You could quite easily attach the result of SendImage to a literal control.

In your C# code:

 
 
 
  
  Image myShinyNewImage = SendImage(someImageObject, approved); myLiteralControl.Controls.Add(myShinyNewImage);
 
  

In your aspx page:

 
 
 
  
  <asp:Literal id="myLiteralControl" runat="server" />
 
  

UPDATE:

As correctly pointed out in the comments, you can't add child controls to a Literal however you can add the control directly to the page.

 this.Controls.Add(SendImage(someImageObject, approved)); 

or add the control to another control that does allow child controls to be added such as a Panel control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM