geminiCoder
geminiCoder

Reputation: 2906

Dynamically Creating ImageButtons

what I want to do is create the following

 for(int i = 0; i < numberOfAnswers; i++){
        imgString = imgString + "<td><asp:ImageButton id='" + questionName + "' ImageURL='Styles/unClicked.png' runat='server' /></td>";
    }

but when I use HTMLTextWriter to write the string out, it attualy writes the tags out exsatly instead of converting them to html.

Do I have to write them in HTML and use javascript to call a method, or is there a way I can do this without getting that complicated?

Upvotes: 0

Views: 86

Answers (3)

Tim M.
Tim M.

Reputation: 54377

You should instantiate the ImageButton objects and add them to the control structure of your page. They will then render their own markup, register for events, etc.

for(int i = 0; i < numberOfAnswers; i++){
    var ib = new ImageButton();
    var td = new HtmlTableCell();

    // assign values, like ID, Image URL, event handlers, etc. here
    ib.ID = "button_" + i;
    ib.ImageUrl = "foo";
    ib.Click += ( sender, e ) => {
        // anonymous event handler
    };

    // "container" can be any control on the page, such as a table row
    container.Controls.Add( td );
    td.Controls.Add( ib );
}

Upvotes: 2

user1466291
user1466291

Reputation:

    for (var i = 0; i < 5; i++)
    {
        ImageButton imgBtn = new ImageButton();
        imgBtn.ID = "question" + i;
        imgBtn.ImageUrl = "Styles/unClicked.png";

        PlaceHolder1.Controls.Add(imgBtn);
    }

PlaceHolder1 is the runat server control, where u'd like to add ur generated buttons.

Upvotes: 1

Lajja Thaker
Lajja Thaker

Reputation: 2041

Use HTML.Encode() method to write string out

check below URL

http://www.dotnetperls.com/encode-html-string

Upvotes: 1

Related Questions