08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

64<br />

CHAPTER 3 ■ WEB FORMS WITH <strong>ASP</strong>.<strong>NET</strong><br />

Creating Controls at Runtime<br />

Because controls are objects, <strong>and</strong> because the page controls are a collection, you can also<br />

create controls at runtime. So, if you consider the previous example, you can add a new<br />

list box to the bottom of the form quite easily with this code:<br />

protected void Page_Load(object sender, EventArgs e)<br />

{<br />

foreach(Control ctrl in Page.Controls)<br />

{<br />

ListBox1.Items.Add(ctrl.GetType().ToString() + ":" + ctrl.ID);<br />

}<br />

theHead.Title = "Dynamically Created Title!";<br />

ListBox newListBox = new ListBox();<br />

newListBox.Items.Add(new ListItem("Item on my Dynamic List"));<br />

Page.Form.Controls.Add(newListBox);<br />

}<br />

Note that you have to add a control to a control container—you cannot add it directly<br />

to the page—so Page.Controls.Add will fail. If you want to add it to the top level of the<br />

page, use Page.Form.Controls.Add, as just shown. Additionally, you can add the control to<br />

an existing panel on the page. For example, you can add one to a named panel (Panel1)<br />

like this:<br />

Panel1.Controls.Add(newListBox);<br />

When you run the application, you can see the new list box on your page (see<br />

Figure 3-8).<br />

Of course, you can also h<strong>and</strong>le events on dynamically created controls. You do so by<br />

adding an event h<strong>and</strong>ler to the object, specifying the event that you want to h<strong>and</strong>le. So,<br />

for example, if you want to h<strong>and</strong>le a SelectedIndexChanged event on a dynamically created<br />

list, you would do this first by assigning the event h<strong>and</strong>ler like this:<br />

newListBox.SelectedIndexChanged +=<br />

new EventH<strong>and</strong>ler(newListBox_SelectedIndexChanged);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!