Skip to content Skip to sidebar Skip to footer

Adding An Image Dynamically In Asp.net C#

I have a book database where i have book information. I have a row where i store the name of the picture of the book i want to display on the page. For example cprog.jpeg Now, i wa

Solution 1:

I am assuming row[8] is your image name... try something like

+"<img src=\""+ row[8].ToString() +"\"></div>"

You will have to put in the path to the image too, that will look like

+"<img src=\"/path/to/image/"+ row[8].ToString() +"\"></div>"

However... the other answerer is correct, this is very messy & will only break your heart later. Databound controls are the way to go, read up on DataGrids and Repeaters... it will be worth your while!

Solution 2:

You're doing several things horribly wrong:

  1. Don't ever concatenate strings like that. Use the StringBuilder class instead.
  2. Don't even build up HTML by concatenating strings. It produces horribly unmaintainable code. If I saw that in a project I was responsible for, I would tell you to fix it immediately. If I saw it in a project I was not responsible for, I would ask your supervisor to tell you to fix it immediately.
  3. Please learn how to use data-bound controls like the Repeater control!
  4. If the database only contains the name, and if the name is part of the URL, then you need to form the complete URL:

    String.Format("http://mysite.com/images/{0}.jpg", row[8]);
    

Solution 3:

Please avoid building HTML like that in your code behind. Instead:

  1. Move all of the mark-up into an aspx file, and out of the code behind.
  2. Switch to using controls instead of bare html: <asp:Image> for the <img> tag, and <asp:Panel> for the <div>s
  3. Wrap the controls in an <asp:Repeater> with an <ItemTemplate>
  4. Use Data Binding to assign the values from your DataTable to properties of the controls

Post a Comment for "Adding An Image Dynamically In Asp.net C#"