2

I want to add image to div, but innerHtml overrides it. How I need to achieve this? This is what I have for now:

Image ThumbImg = new Image();
ThumbImg.ImageUrl = ImgUrl; 

HtmlGenericControl divContent = new HtmlGenericControl("div");
divContent.Controls.Add(ThumbImg);
divContent.InnerHtml = Desc;

If I move divContent.Controls.Add(ThumbImg); line to the end, then it adds an image, but to the end of content and I want image to be in beginning of the content.

4
  • What is in "Desc"? If it is just a string could you add the image markup to it? Commented Feb 11, 2013 at 9:50
  • Instead of adding image in divContent, you should add Image in Desc content using '<img>' tag. It may help you. Commented Feb 11, 2013 at 9:52
  • "Desc" is a string. How can I add image to "Desc" then? Commented Feb 11, 2013 at 9:53
  • you can add it like this. See my post. Commented Feb 11, 2013 at 9:55

5 Answers 5

4

Add "img" tag into Desc. Then set it in div's innerhtml.

Desc=Desc+ "<img src=" + ImgUrl + " />";
divContent.InnerHtml = Desc;

else

Image img = new Image();
img.ImageUrl = ImgUrl;
divContent.Append(img);
divContent.Append(Desc);
Sign up to request clarification or add additional context in comments.

1 Comment

There's no function called Append.
2

Use this to show image in Div

div.Style("background-image") = Page.ResolveUrl("~/Images/xyz.JPG")

1 Comment

Good approach. I would do like this div.Style.Add("background-image", Page.ResolveUrl("~/Images/xyz.JPG"));
1

When you set InnerHtml you overwrite all Controls you added (as you found out).

Solution: add another control, such as a LiteralControl where you put in the text.

Image ThumbImg = new Image();
ThumbImg.ImageUrl = ImgUrl; 

HtmlGenericControl divContent = new HtmlGenericControl("div");
divContent.Controls.Add(ThumbImg);
LiteralControl lit = new LiteralControl();
lit.Text = Desc;
divContent.Controls.Add(lit);

Or, as an alternative, use the Label control. Difference: Label uses escaping before showing your text, LiteralControl doesn't.

Comments

1

You can add it like this.

Desc +=  "<img id=\"img1\" src="+ ImgUrl + " />";
divContent.InnerHtml = Desc;

2 Comments

<img> has a self closing tag. Otherwise solution is working, but you placed your answer later then @Hiral.
yes you are right @Morpheus. Thanks for your positive response.
0

Not sure, but would this work:

divContent.InnerHtml += Desc;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.