1

Is there a way I could dynamically add a Image1 to the while loop in the below code (contained within the div) By this I mean actually adding an asp image to the div? via the code. At the moment as I see it the code looks for an asp image but Ive seen no way you can "add" it to my dynamic content:

using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
{
    using (OdbcDataReader reader = cmd.ExecuteReader())
    {
        var divHtml = new System.Text.StringBuilder();
        while (reader.Read())
        {
            divHtml.Append("<div id=test>");
            divHtml.Append(String.Format("{0}", reader.GetString(0)));
            divHtml.Append("</div>");
        }
        test1.InnerHtml = divHtml.ToString();
    }
}

Thought I had it with this:

        var divHtml = new System.Text.StringBuilder();
        while (reader.Read())
        {
                    divHtml.Append("<div id=test>");
                    divHtml.Append(String.Format("{0}", reader.GetString(0)));
                    Image img = new Image();
                    img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
                    divHtml.Append(img);
                    divHtml.Append("</div>");
        }
        test1.InnerHtml = divHtml.ToString();

I get a funky output tho?

See picture:

enter image description here

Ive also tryed this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.Odbc;
    using System.Web.UI.WebControls.Image;
    using System.Web.UI.HtmlControls.HtmlGenericControl;
    using System.IO;

    public partial class UserProfileWall : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string theUserId = Session["UserID"].ToString();
            PopulateWallPosts(theUserId);
        }
        public static string RenderHtmlString(this System.Web.UI.HtmlControls.HtmlGenericControl htmlControl)
        {
            string result = string.Empty;
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                var writer = new System.Web.UI.HtmlTextWriter(sw);
                htmlControl.RenderControl(writer);
                result = sw.ToString();
                writer.Close();
            }
            return result;
        }
        private void PopulateWallPosts(string userId)
        {
            using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
            {
                cn.Open();
                using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
                {
                    using (OdbcDataReader reader = cmd.ExecuteReader())
                    {


                        var divHtml = new System.Text.StringBuilder();
                        while (reader.Read())
                        {
                            using (StringWriter sw = new StringWriter())

                            divHtml.Append("<div id=test>");
                            divHtml.Append(String.Format("{0}", reader.GetString(0)));
                            Image img = new Image();
                            img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
                            divHtml.Append(img.RenderHtmlString());
//this line
                            divHtml.Append("</div>");
                        }
                        test1.InnerHtml = divHtml.ToString();
                    }
                }
            }
        }

But RenderHtmlString has no definition?

12
  • Yes why couldn't you? You should really spell out your doubts on this one to help us better address them with you Commented Mar 23, 2011 at 14:12
  • possible duplicate of how do you set css to add an asp img? Commented Mar 23, 2011 at 14:17
  • Garrith: Generally speaking you should update your original question with new information instead of starting a completely new question. Please close this and just update the question you started 20 minutes ago. Commented Mar 23, 2011 at 14:18
  • 1
    nope not at all a duplicate? I recieved an answer that you cant add asp images via css now I have to find a new route hence the question above! Commented Mar 23, 2011 at 14:19
  • 1
    The problem with the updated code is that Image.ToString() (what you're doing) returns System.Web.UI.WebControls.Image so you're getting what's expected. You need to render it as text. See my answer below for a link that includes a Generic method (that you put in any class, and then call as img.RenderHtmlString() so you could use what you have and change divHtml.Append(img); to divHtml.Append(img.RenderHtmlString()); if you include that Generics method in your project. Commented Mar 23, 2011 at 15:06

4 Answers 4

4
HtmlGenericControl("div") divHtml = new HtmlGenericControl("div");
divHtml.Controls.Add( HtmlImage image = new HtmlImage{ Src = "pathgoeshere" } );

Presumably you will need to also return this as a string? If so, try this handy Generic http://www.refactory.org/s/render_html_string_from_htmlgenericcontrol/view/latest but really do what everyone else is suggesting and use the power of <asp:PlaceHolder to it's fullest and just add this returned control to the placeholder's control collection.

Sign up to request clarification or add additional context in comments.

3 Comments

You tried what exactly? I have no idea what you did or did not do.
see edit I tryed your method? Not sure if its correct tho. Also renderhtmlstring has no definition?
@Garrith did you add the Generic method that I linked to into a globally available class in your project? Until then "RenderHtmlString" won't have a definition
3

No, you cannot add a server control to a literal representation of a DOM element.

I am not sure what type of control "test1" is, but you should change it out to a PlaceHolder control and do the following (not tested!):

 using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
        {
            using (OdbcDataReader reader = cmd.ExecuteReader())
            {
                var divHtml = new System.Text.StringBuilder();
                while (reader.Read())
                {
                    System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                    div.ID = "test";
                    div.InnerHtml = String.Format("{0}", reader.GetString(0));
                    Image img = new Image();
                    img.ImageUrl = "~/images/test.jpg";
                    img.AlternateText = "Test image";
                    div.Controls.Add(img);
                    test1.Controls.Add(div);
                }
                test1.InnerHtml = divHtml.ToString();
            }
        }

Hope this helps!

1 Comment

My code is really just for reference, it will likely need to be modified to suit your specific need. step through the code in debug mode to make sure you are getting the result etc and maybe post your code if you need specific help.
1

Just a bit of a concern. You're dynamically building your SQL string. Make sure you sanitize the "userid" variable.

You can dynamically create images by doing this:

System.Web.UI.WebControls.Image img = new Image();
img.ImageUrl = "~/img/image1.jpg";

Do you know the images you wish to use already? Are the images or the image source located within your database?

2 Comments

the problem is that he can't inject the new WebControl into his string. If he were to use a HtmlGenericControl("div") he wouldn't have this problem.
the url is stored in a seperate table named Pictures and the colum being picturepath that was my next question how I can join it on to my sql syntax atm, there linked via the UserID
1

Try using a placeholder

Image img = new Image(); // instantiating the control
img.ImageUrl = "~/myimage.gif"; // setting the path to the image
placeholderpicture.Controls.Add(img);

From http://forums.asp.net/t/1308158.aspx/1

6 Comments

hmmm the thing is the divs are dynamic, how do I add a placeholder to something thats not there?
this doesnt add the img to the div?
Dynamically add divs to a placeholder, and add images to the divs? Not sure if I understand the issue.
does the placeholder go inside the div?
have a look at the img i have in my post and you will see what it looks like, User posts something its inserted into mysql database then reloaded on the same page which is chucked into a div named =test under which these test divs reside test1 div, I have to find a way to add each image to each div=test
|

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.