Dynamically Adding Controls

  • Thread starter Thread starter micah
  • Start date Start date
M

micah

I am somewhat new to the .net framework, and I am completely stumped on
something that I feel should be relatively simple.

1. I need to dynamically create controls on a web page

This is not a problem.

2. In order to format these dynamic controls how I want them, I first
decided to put them in a Table Control.

This worked fine, unfortunately the Table Control doesnt remember
viewstate so it wont work for what I need.

3. To get around the viewstate problem I decided to go forward by using
a DataGrid. I discovered I could dynamically add rows to a DataTable
and then bind that DataTable to the DataGrid

Thats fine and dandy, works ok.

4. When I assign an actual control like a TextBox to one of the items
in the myDataTable.NewRow()["myColumn"], all I get is
"System.Web.UI.WebControls.TextBox" and not the actual control itself.

I figured I could fix this by specifying the type on the columns for
the datatable via
System.Type.GetType("System.Web.UI.WebControls.TextBox"), but this
returns NULL and creates an error.

Can anyone help clear this up for me? One extremely frustrated
programmer. -micah
 
You can't add a TextBox control to the data table. What you want to do
is handle all of the controls in the data grid, and the data in the
data table. To add the TextBox programatically, and have it show
render correctly, you need to add it to a controls collection (don't
forget to assign an ID and enable view state). I think you should be
able to figure it out with the links i provided at the bottom.

Basicly, you want to do this

1. Bind the current data to the datagrid.
2. Add the text box to the datagrid (wherever you have it going) on the
OnItemDataBound event (see the code project link)
3. when saving data do the following
3a. create a datarow variable and assign it to table.newrow() (see
microsoft link)
3b. add values to data row
3c. add the datarow to the datatable
4. rebind the grid to the table

These links may help,
http://www.codeproject.com/aspnet/griddemo.asp
http://msdn.microsoft.com/library/d.../html/frlrfsystemdatadatacolumnclasstopic.asp
http://msdn.microsoft.com/library/d...f/html/frlrfsystemdatadatatableclasstopic.asp
http://msdn.microsoft.com/library/d...ml/frlrfsystemdatadatatableclassrowstopic.asp

on the microsoft links, check out the methods and properties sections.

HTH,
Darren Kopp
http://blog.secudocs.com/
 
Back
Top