Pergunta

How do I perform actions (e.g change text) when I know the ID of the div that I created dynamically with this code:

Stringbuilder sb = new Strinbuilder();
sb.AppendLine("<div id='example'>I want to change this text</div>");

//Examples using a literal, placeholder or a lable:

litExample.Text = sb.ToString();

phExample.Text = sb.ToString();

lblExample.Text = sb.ToString();



//Call id example and change "I want to change this text" , to something else.
//How do I do this?

Thanks in advance.

Foi útil?

Solução

First Of All make sure you have added following namespaces:

using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text;

and add following method to your code:

  public string RenderControl(Control ctrl)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter tw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(tw);

        ctrl.RenderControl(hw);
        return sb.ToString();
    }

and change your code to following:

        //StringBuilder sb = new StringBuilder();
        HtmlGenericControl myDiv = new HtmlGenericControl("div");
        myDiv.InnerText = "I want to change this text";

        //Make sure asp.net does not add any prefix to your Id "example"
        myDiv.ClientIDMode = System.Web.UI.ClientIDMode.Static;
        myDiv.ID = "example";

        //Examples using a literal, placeholder or a lable:

        litExample.Text = RenderControl(myDiv);

        phExample.Text = RenderControl(myDiv);

        lblExample.Text = RenderControl(myDiv);

        //Do Stuff with myDiv as typical control

Outras dicas

When the page has already been rendered, you might want to do this with javascript. Something like:

document.getElementById('example').innerHTML = 'New text';

If the page has not been rendered yet, you probably need to adjust the string directly inside your stringbuilder, or at each instance where you use it, or maybe use a different approach altogether, but you don't provide enough information in your question to say anything useful about that.

Just a little thing, you're gonna have a bad time with JS since all your DIVs share the same ID...

You could solve the problem by setting the IDs manually AND setting the ClientIDMode on Static to prevent an automatic creation as pointed by Seyed.

You could use a custom CSS class to select all the items at once.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top