Write web controls out to a page and associating event handlers


G

Guest

Hey all, I realize this must be a fairly common requirement in ASP.NET but I
have yet to come across the right way to do it.

Basically, right now I have a single asp:label on my webpage and I am
writing out to the Text property of that Label object.

However, now I would like to write a control like a button to that Text and
associate an event handler with that button.

How should I do that - or am I going about this in the wrong way - i.e.
should I be creating my own custom web control?

Anyway, here is my attempt at writing an asp:button out to the page and
associating an event handler with it:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Button button = new Button ();
button.Click += new EventHandler(nextButtonClick);
htw.Write(button.);
htw.Flush();
MyLabel.Text += sb.ToString();

Thanks for any help,
Novice
 
Ad

Advertisements

J

John Saunders

Novice said:
Hey all, I realize this must be a fairly common requirement in ASP.NET but
I
have yet to come across the right way to do it.

Basically, right now I have a single asp:label on my webpage and I am
writing out to the Text property of that Label object.

However, now I would like to write a control like a button to that Text
and
associate an event handler with that button.

How should I do that - or am I going about this in the wrong way - i.e.
should I be creating my own custom web control?

I strongly recommend that you use a property named "Text" for text and
nothing else. Even if something else (like HTML) works today, I'd worry that
the authors of the control might forget that "Text" is not juts used for
Text, and may break your code by making the control work according to their
assumptions...

If you want to dynamically display one of several controls (like your button
example), there are several ways to do this. The simplest is to place all of
the possible controls on the page with Visible set to false. Then, at
run-time, change the Visible property of the control you want to see to
true. The overhead of this isn't as high as it sounds, since a control with
the Visible property clear will not render any HTML.

Another way is to put a Panel control on the page, and at run-time, add the
desired control (or controls) to the Panel:

Button myButton = new Button();
myButton.Text = "Button";
myPanel.Controls.Add(myButton);
 

Top