I assume by now, unless you are just learning .NET, that everyone is familiar with the standard Web Form Elements. Radio buttons, radio button lists, check boxes, check box lists, text boxes, etc. What this article aims to do is present a solution for generating dynamic form elements and retrieving there values. Some of you may be asking what is the reason for this? Well, lets say you have several check box lists that you need to generate from a database, but you don't know how many there are going to be. In this case you need to dynamically generate form elements from a database. You would normally do this in the Page_Load function like this:
CheckBoxList chkList1 = new CheckBoxList();
chkList1.ID = "SomeList";
// populate the check box list
for(int i = 0; i < nElements; i++)
{
ListItem listItem = new ListItem();
listItem.Value = sNameValue[0];
listItem.Text = sNameValue[1];
chkList1.Items.Add(listItem);
}
// Do some other stuff and add the check box list to the page
someTableObject.Controls.Add(chkList1);
Now that you have dynamically generated your check box list and you have a pretty form displayed, how do you get the information that the user entered out when they click submit? Since you generated the check box list dynamically you cant just reference the name. You could use Request.Form but this gets a bit messy and if you don't know the exact name then your screwed.
How about this: do basically the same thing you did in the Page_Load function but this time find the check box list control in your page. Like this:
Private void btnSubmit_Click(...)
{
CheckBoxList chkList1 = (CheckBoxList)this.FindControl("SomeList");
for(int i = 0; i < chkBoxList1.Items.Count; i++)
{
if(chkBoxList1.Items[i].Selected == true)
{
// Do something with the value
blah = chkList1.Items[i].Value;
}
}
}
You can do this with any control. This comes in handy when you want to build forms from a database, or any data source for that matter. When you don't know how many elements you will need have no fear, there is a way to get the information out J
If you have any questions please feel free to email me at ruts@datausa.com
Matt Rutledge
Lead Developer
DATA, Incorporated
1777 S. Bellaire Street, Suite Ground Zero
Denver, CO 80222
303.708.9708
303.708.8709 (Fax)
www.datausa.com
DATA is a specialist in digital visual media: 3D-computer animation,
multimedia design and development (CD-ROM and DVD), Web development and
design with full e-commerce applications, database programming, on-line
training, hosting, and complete video production and streaming.