Dynamic Controls in ASP.NET

My 10th grade English teacher Mrs. Houghton once made me stay after school for "Comma Detention" (no, I'm not kidding) because I couldn't remember all of the "5 Comma Rules" for a quiz in her class. The only comma rule that still sticks in my head from that list was #5, Do Not Use Unnecessary Commas.  This has inspired me to write my own rules...

Datagrid Girl's Rules for Dynamic Controls in ASP.NET.
Rule #1) Don't create controls dynamically unless you really have to.  I can't tell you how many times I've been answering Datagrid questions for people and in about the 4th message they point out, "Oh, I'm creating this grid dynamically, does that matter?"  Yes, it matters.  The code for working with dynamically created controls is just plain harder.

Rule #2) If what you're creating dynamically doesn't change based on any user inputs or other criteria, there's really no reason to create the thing dynamically.  I've met some people who just like to create controls dynamically so all the code is in the .vb file rather than the ASPX.  To me that seems just plain silly.  The whole point of codebehind .vb vs. ASPX is to have separation of presentation and code, so if you're creating your presentation in code, you're missing the point.  (There are exception to this however, when you do need to do presentation stuff in code, but those should be just that--exceptions).

Rule #3) If what you're creating dynamically repeats based on some kind of loop, either from a database, an array, the file system, or similar, again you don't need to use dynamic controls.  This is where a Repeater comes in handy.  You can use a Repeater to repeat just about anything, including repeating a Datagrid for every row in a database table, for example.

Rule #4) If you do create dynamically, don't expect that control to exist after postback.  If your situation doesn't apply to rules 1-3 and you do have to use dynamic controls, you must recreate them after each postback if you expect to A) read a value from it or B) have it fire an event.

Rule #5) Do not use unneccessary dynamic controls.  (Sorry, couldn't resist).

Datagrid Girl

 

 

Published Thursday, March 27, 2003 8:35 PM by datagridgirl

Comments

# re: Dynamic Controls in ASP.NET

Hi
Im working with Visual Studio.NET.
Using ASP.NET/VB.NET.

I need to build form that will show each time different results (fields) in a datagrid.(I have 3 different SQL queries)
The datagrid will contain BoundColumns,HyperLinkColumns, TemplateColumns (text boxes), Validators. And a lot of hidden fields.
My questions is, because the DataGrid suppose to work each time with different fields, should I build 3 different datagrids (I have 3 types or results) or 1 dynamic datagrid?

After you answer me, if you please can send me a url that explain how to do that.

Thanks a lot!!

Thursday, May 01, 2003 1:42 PM by Ran

# re: Dynamic Controls in ASP.NET

I have a strange problem with the datagrid I'm using. I have created my datagrid Non-dynamically, and it works. The only problem is that when I'm in VB.NET, and I have the aspx file open, if I click on the "Design" tag, and then go back to the "HTML" tag, all my HTML and ASP code dissapears! My entire datagrid just goes up in smoke, the code just isn't there anymore.

Why would VB.NET do that? Any idea?
(trueneutral@hotmail.com)

Tuesday, September 23, 2003 6:18 PM by Jesse Morrison

# re: Dynamic Controls in ASP.NET

Dear Datagrid Girl,
Thank you for your advice. My thinking on this is that I want to create one basic set of generic asp.net functions that will render pages for me based on database query results. I have a table structure in which I define the controls and where they belong and what their display options are. If it is a listbox or combobox or table data then I fill in the data according to a subquery defined in the database. This all works great. I want to do this so that I can create applications faster by defining the application interfaces in the database. Toss in my handy dandy generic aspx and aspx.vb code and voila, new web interface to my database. Then all I need to do is focus on the queries I need. I have a working version of this technique from vb6 and it has been very good to me. Generic coding is a real time saver. And to get there with asp.net I will need to be able to load my controls, including the datagrid, dynamically if possible. Now if I could only get the datagrid events to fire... :)

Friday, October 17, 2003 7:13 PM by VBWyrde

# managing Dynamic Controls in ASP.NET

please

Wednesday, March 24, 2004 2:57 AM by laxmi

# re: Dynamic Controls in ASP.NET

Can you explain to me why I am unable to retrieve the ViewState values for the controls I am dynamically creating in this DataList? I am re-creating the controls in my Page_Load, but I cannot see the values that were set by the user on the web page.

ASCX Code:

<table id="table1" runat="server" width="950" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div
style="BORDER-RIGHT: gray 1px solid; PADDING-LEFT: 5px; BACKGROUND-IMAGE: url(Images/greybar_20.gif); MARGIN-LEFT: 0px; BORDER-LEFT: gray 1px solid; WIDTH: 950px; PADDING-TOP: 2px; BORDER-BOTTOM: black 1px solid; HEIGHT: 20px">
<asp:Label ID="labTitle" Runat=server Font-Name="Arial" Font-Size="8pt" Font-Bold=True ForeColor="Navy">
Select Survey Types
</asp:Label>
</div>
<asp:Panel id="panSearch" runat="server" BorderStyle="Outset" BorderWidth="2px" height="55" Width="950" HorizontalAlign="Left" BackColor="lightgoldenrodyellow">
<table cellpadding="0" cellspacing="0" border="0" style="MARGIN: 5px 5px 5px 5px;">
<tr>
<td>
<asp:CheckBoxList id="cklSurveys" runat="server"
RepeatDirection="Horizontal"
RepeatColumns="5"
Font-Size="8pt"
ForeColor="maroon"
Font-Bold="True"
AutoPostBack="True">
</asp:CheckBoxList>
</td>

<td width="25"></td>

<td>
<asp:Button ID="btnCalcPrice" Runat="server" CssClass="StdText" ForeColor="DarkGreen" Text="Calculate Price"></asp:Button>
<asp:Button ID="btnSelectActivities" Runat="server" CssClass="StdText" ForeColor="navy" Text="Select Activities"></asp:Button>
</td>
</tr>
</table>
</asp:Panel>
</td></tr>

<tr><td style="WIDTH: 950px; HEIGHT: 10px; BACKGROUND-COLOR: white"></td></tr>

<tr><td>
<div style="BORDER-RIGHT: gray 1px solid; PADDING-LEFT: 5px; BACKGROUND-IMAGE: url(Images/greybar_20.gif); MARGIN-LEFT: 0px; BORDER-LEFT: gray 1px solid; WIDTH: 950px; PADDING-TOP: 2px; BORDER-BOTTOM: black 1px solid; HEIGHT: 20px">
<span id="spanGridTitle" runat="server" style="FONT-WEIGHT:bold;FONT-SIZE:8pt;COLOR:navy;FONT-FAMILY:Arial">
Answer Survey Questions</span><span id="spanGridCount" runat="server" style="FONT-WEIGHT:bold;FONT-SIZE:8pt;COLOR:maroon;FONT-FAMILY:Arial"></span></div>

<asp:Panel id="panGrid" runat="server" BorderStyle="Outset" BorderWidth="2px" Width="950" BackColor="lightgoldenrodyellow" style="OVERFLOW: auto">
<asp:DataList ID="lstQuestions" Runat="server"
RepeatColumns="2"
RepeatDirection="Vertical" RepeatLayout="Table" GridLines="Horizontal" BorderColor="whitesmoke"
ForeColor="Black" Font-Size="8pt" Font-Name="Arial" BackColor="White" BorderWidth="1px" EnableViewState="True">
<AlternatingItemStyle BackColor="White" ForeColor="navy"></AlternatingItemStyle>
<ItemStyle BackColor="white" ForeColor="navy"></ItemStyle>
<HeaderStyle ForeColor="Black" BackColor="LightGrey" HorizontalAlign="Left" Font-Size="10pt"></HeaderStyle>
<HeaderTemplate>
<span style="WIDTH: 175px; TEXT-ALIGN: left">Question</span>
<span style="WIDTH: 250px; TEXT-ALIGN: left">Answer</span>
<span style="WIDTH: 175px; TEXT-ALIGN: left">Question</span>
<span style="WIDTH: 250px; TEXT-ALIGN: left">Answer</span>
</HeaderTemplate>
<AlternatingItemTemplate>
<span id="altQuestion" runat="server" style="WIDTH: 175px"></span>
<span id="altAnswer" runat="server" style="WIDTH: 250px"></span>
</AlternatingItemTemplate>
<ItemTemplate>
<span id="itemQuestion" runat="server" style="WIDTH: 175px"></span>
<span id="itemAnswer" runat="server" style="WIDTH: 250px"></span>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</td></tr>

<tr><td style="WIDTH: 950px; HEIGHT: 10px; BACKGROUND-COLOR: white"></td></tr>


</table>

****** CODE-BEHIND: ********
private void Page_Load(object sender, System.EventArgs e)
{
_LoadControls();
_LoadQuestions();
}

private void _LoadQuestions()
{
string serviceList = "";
foreach(ListItem item in cklSurveys.Items)
{
if (item.Selected == true)
{
serviceList += "-" + item.Value;
}
}
if (serviceList.Length > 0) serviceList = serviceList.Substring(1);
ArrayList qList = _questions.GetQuestionList(serviceList);
lstQuestions.DataSource = qList;
lstQuestions.DataBind();
}


private void lstQuestions_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRow qRow = _questions.GetQuestion(e.Item.DataItem.ToString());
e.Item.Controls[1].Controls.Add( new LiteralControl( qRow["desc"].ToString() ) );
e.Item.Controls[3].Controls.Add( _GetQuestionControl(qRow) );
}
}

private Control _GetQuestionControl(DataRow qRow)
{
switch(qRow["type"].ToString())
{
case "txt" :
TextBox txt = new TextBox();
txt.CssClass = "StdLabel";
txt.ID = qRow["id"].ToString();
txt.Width = Unit.Pixel( Convert.ToInt32( qRow["width"].ToString() ) );
return txt;

case "ddlb" :
DropDownList cmb = new DropDownList();
cmb.CssClass = "StdLabel";
cmb.ID = qRow["id"].ToString();
cmb.DataSource = _questions.GetQuestionOptions(qRow["id"].ToString());
cmb.DataTextField = "desc";
cmb.DataValueField = "id";
cmb.DataBind();
return cmb;

}
return new LiteralControl("");
}


Wednesday, March 31, 2004 5:50 PM by Randy Leinen

# re: Dynamic Controls in ASP.NET

Nice !!! to learn

Tuesday, April 27, 2004 10:01 AM by Mahesh

# re: Dynamic Controls in ASP.NET

how to add dynamically created RadioButtonLists to the ArrayList?

how to access each RadioButtonList from the ArrayList?

Anyone...

Friday, July 02, 2004 8:14 AM by srinija

# re: Dynamic Controls in ASP.NET

You should not be coding.

Period.

Ever.

Please don't post anymore "helpful" rules that contain false information.

Here's a hint: A Repeater IS a dynamic control.

Monday, July 12, 2004 10:00 PM by CSharpIsBetter

# re: Dynamic Controls in ASP.NET

RULE #6: There are always excetions to every rule.

Wednesday, July 21, 2004 1:59 PM by caveman

# re: Dynamic Controls in ASP.NET

or 'exceptions';)

Wednesday, July 21, 2004 1:59 PM by caveman

# re: Dynamic Controls in ASP.NET

CSharpIsBetter - you're a moron.

A dynamic control is one created programatically , not one placed in the aspx page. YOU should not be coding...ever...period...

Monday, July 26, 2004 11:27 AM by bobTheBuilder

# re: Dynamic Controls in ASP.NET

hi ,

I need to create multiple dynamic controls like text box, combobox, radio button. I need to implement the then in web page like "form designer" . then i may need to handle it in such way it should exist during psotback and also to maintain its state.

How can we handle multiple dynamic controls during postback and to maintain its view state. can i have ur valuable suggestions on this

Monday, June 11, 2007 8:48 AM by krishna

# re: Dynamic Controls in ASP.NET

I found your advice valuable. Great to get it from a girl for a change.

Friday, July 27, 2007 11:37 AM by Roman

# re: Dynamic Controls in ASP.NET

hi!,

 Thanks For Ur Gr8 Solutions on Dynamic Datagrid

Wednesday, September 19, 2007 6:21 AM by sujit

# re: Dynamic Controls in ASP.NET

can you please  teel me how to add multiple labels vertically one below the other in a datagrid cell dynamically????

Thursday, November 22, 2007 6:44 PM by gunner

# re: Dynamic Controls in ASP.NET

Hi

    i need to make dynamic multiple checkbox list in panel

    problem after any postback have done

    how to managed the post

    what should i do?

Wednesday, January 09, 2008 4:21 AM by vikash

# re: Dynamic Controls in ASP.NET

how to add multiple labels  to datagrid row

Friday, May 16, 2008 7:56 AM by haranath

# re: Dynamic Controls in ASP.NET

i am using a list box inside datagrid and this listbox is bound with some datasource.When i am saving data selected in database it is working fine. But how can i display those  selected data's in listbox  of  datagrid.

Tuesday, July 22, 2008 12:30 PM by arvind

# re: Dynamic Controls in ASP.NET

hi this is not a comments but i need some help in how to make codes in datagrid in vb6 when calculating the grade of the student after i input it in the datagrid it will automatically calculate the average of the student.please i need your help..please reply me

Wednesday, September 10, 2008 5:25 AM by jeremy

# re: Dynamic Controls in ASP.NET

Hey generally I agree with the admonition about Dynamic controls. Especially for beginners. But there gets to be a point (over time) where generating controls dynamically will start to pay off and can save you TONS of time.

By the way, I think there is still not a general understanding of the ASP page lifecycle. If you are serious about coding ASP pages... you've got to understand how things work on every ASP request, behind the scenes.

Oh - you know about the life cycle? Well then you understand that EVERYTHING is .... dynamic.

Wednesday, February 18, 2009 2:51 PM by SugarBomb

# re: Dynamic Controls in ASP.NET

thanks

Sunday, March 22, 2009 11:50 PM by sagnikmukh

# re: Dynamic Controls in ASP.NET

I love you Datagrid Girl!!!

Monday, March 30, 2009 5:05 PM by Bill Gates

# re: Dynamic Controls in ASP.NET

I want to create text boxes according to values get fetched from database

Wednesday, April 14, 2010 3:05 AM by Gajanan

# re: Dynamic Controls in ASP.NET

Dynamically I have create the server side textbox control then i call some other server side function via button click the textbox control has cleared. how will restrict this  

Saturday, May 29, 2010 4:53 AM by Gunasekaran

Leave a Comment

(required) 
(required) 
(optional)
(required)