Create Dynamic Form In ASP.NET, And Retrieve Values From That

In this article, we will learn how we can create a dynamic form in ASP.NET. Here, dynamic means that we will create the controls at run time.
 
Introduction

Suppose someone asks you to create a form in ASP.NET. You will say, "It's easy". You will go to an aspx page, drag the controls from toolbox, and the form is ready. But, the person doesn't  want you to drag the controls from the toolbox or write in aspx page. Our requirement is to create the controls at run time. So, is that doable? Yes! It is. We can do this in two ways. I will describe here only one way. However, you will also get a hint of the second. So, let's start the code.
 
First, look into the requirement.
 
Suppose, we have a requirement where we need to generate the following form fields and their corresponding field types. This, we need to do dynamically at the run time and have to get the values from them. So, our requirement is clear. Always understand the requirement first because without knowing what exactly we need to do, we can't code perfectly.
 
Requirement

 
 
From the above image, we know what field we will have in the form and what type of controls will be needed for those fields. For example, we have Firstname which will take Textbox.
 
So, let's start doing the code.
 

In the above image, I created a function according to our need. In this function, I created a data table with three columns (Fieldname, Fieldtype, and Fieldvalue). So now, our frame is ready. Let's fit it into the form. Let's create another function in which we will create the ASP.NET controls which will return the datatable according to the current function.
Dynamic controls function 
  1. public void CreateDynamicControls()  
  2.     {  
  3.         DataTable dt = new DataTable();  
  4.         dt = CustomFields();  //calling the function which describe the fieldname and fieldtype
  5.         if(dt.Rows.Count>0)  
  6.         {  
  7.             for(Int32 i=0;i<dt.Rows.Count;i++)  
  8.             {  
  9.                 HtmlGenericControl tr = new HtmlGenericControl("tr");  
  10.                 HtmlGenericControl td = new HtmlGenericControl("td");  
  11.                 HtmlGenericControl td1 = new HtmlGenericControl("td");  
  12.   
  13.                 String FieldName=Convert.ToString(dt.Rows[i]["FieldName"]);  
  14.                 String FieldType = Convert.ToString(dt.Rows[i]["FieldType"]);  
  15.                 String FieldValue = Convert.ToString(dt.Rows[i]["FieldValue"]);  
  16.   
  17.                 Label lbcustomename = new Label();  
  18.                 lbcustomename.ID = "lb" + FieldName;  
  19.                 lbcustomename.Text = FieldName;  
  20.                 td.Controls.Add(lbcustomename);  
  21.                 tr.Controls.Add(td);  
  22.   
  23.                 if (FieldType.ToLower().Trim()=="textbox")  
  24.                 {  
  25.                     TextBox txtcustombox = new TextBox();  
  26.                     txtcustombox.ID = "txt" + FieldName;  
  27.                     txtcustombox.Text = FieldValue;  
  28.                     td1.Controls.Add(txtcustombox);  
  29.                 }  
  30.                 else if(FieldType.ToLower().Trim() == "checkbox")  
  31.                 {  
  32.                     CheckBox chkbox = new CheckBox();  
  33.                     chkbox.ID = "chk" + FieldName;  
  34.                     if(FieldValue=="1")  
  35.                     {  
  36.                         chkbox.Checked = true;  
  37.                     }  
  38.                     else  
  39.                     {  
  40.                         chkbox.Checked = false;  
  41.                     }  
  42.                     td1.Controls.Add(chkbox);  
  43.                 }  
  44.                 else if (FieldType.ToLower().Trim() == "radiobutton")  
  45.                 {  
  46.                     RadioButtonList rbnlst = new RadioButtonList();  
  47.                     rbnlst.ID = "rbnlst" + FieldName;  
  48.                     rbnlst.Items.Add(new ListItem("Male","1"));  
  49.                     rbnlst.Items.Add(new ListItem("Female""2"));  
  50.                     if(FieldValue!=String.Empty)  
  51.                     {  
  52.                         rbnlst.SelectedValue = FieldValue;  
  53.                     }  
  54.                     else  
  55.                     {  
  56.                         rbnlst.SelectedValue = "1";  
  57.                     }  
  58.                     rbnlst.RepeatDirection =RepeatDirection.Horizontal;  
  59.                     td1.Controls.Add(rbnlst);  
  60.                 }  
  61.                 else if(FieldType.ToLower().Trim() == "dropdownlist")  
  62.                 {  
  63.                     DropDownList ddllst = new DropDownList();  
  64.                     ddllst.ID = "ddl" + FieldName;  
  65.                     ddllst.Items.Add(new ListItem("Select""0"));  
  66.   
  67.                     if(FieldName.ToLower().Trim()=="state")  
  68.                     {  
  69.                         ddllst.Items.Add(new ListItem("Alabama""AL"));  
  70.                         ddllst.Items.Add(new ListItem("Alaska""AK"));  
  71.                         ddllst.Items.Add(new ListItem("Arizona""AZ"));  
  72.                         ddllst.Items.Add(new ListItem("California""CA"));  
  73.                         ddllst.Items.Add(new ListItem("New York""NY"));  
  74.                     }  
  75.                     else if(FieldName.ToLower().Trim() == "job")  
  76.                     {  
  77.                         ddllst.Items.Add(new ListItem("Developer""1"));  
  78.                         ddllst.Items.Add(new ListItem("Tester""2"));  
  79.                     }  
  80.                     if (FieldValue != String.Empty)  
  81.                     {  
  82.                         ddllst.SelectedValue = FieldValue;  
  83.                     }  
  84.                     else  
  85.                     {  
  86.                         ddllst.SelectedValue = "0";  
  87.                     }  
  88.                     td1.Controls.Add(ddllst);  
  89.                 }  
  90.                 tr.Controls.Add(td1);  
  91.                 placeholder.Controls.Add(tr);  
  92.   
  93.                 //Add button  after last record  
  94.                 if (i==dt.Rows.Count-1)  
  95.                 {  
  96.                     tr = new HtmlGenericControl("tr");  
  97.                     td = new HtmlGenericControl("td");  
  98.                     Button btnSubmit = new Button();  
  99.                     btnSubmit.ID = "btnSubmit";  
  100.                     btnSubmit.Click += btnsubmit_Click;  
  101.                     btnSubmit.OnClientClick = "return ValidateForm();";  
  102.                     btnSubmit.Text = "Submit";  
  103.                     td.Controls.Add(btnSubmit);  
  104.                     td.Attributes.Add("Colspan""2");  
  105.                     td.Attributes.Add("style""text-align:center;");  
  106.                     tr.Controls.Add(td);  
  107.                     placeholder.Controls.Add(tr);  
  108.                 }  
  109.             }  
  110.               
  111.         }  
  112.           
  113.     } 
I created the above function for creating the dynamic controls. We called the function in which we created the data table with fieldname, fieldtype etc. On the basis of that function, we used a loop and got the fieldname and fieldtype one by one and made the check.
For example, we have firstname at first row and have the type textbox, So, we made a check if the type is textbox.
Then, we went into this block and created a control from the class Textbox by giving it attributes, like id value dynamically, nothing static and will add that in the HtmlGenericControl. We created table row and table data, the same way we did for other controls. At last, we checked if the for loop is running for last count. Then, we added the submit button, client click event, and click event. After this, we added it to the Generic control. That's it.
 
Now, it is the time to run it and see the output. We call this function on Page_Load event, outside ispostback property; because, we need to get the output also. If we call this function within IsPostBack, we can't find the controls on the page.
 
Page load event
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         CreateDynamicControls();  
  4.   
  5.     } 
So, hit the F5 button and see the output. It should be similar to the below image.



Our form is ready. If we have taken the controls on aspx page, it will work fine. So, let's check the aspx page.



You can see in the above image of Aspx page, we don't have any form created in this page. We just have a placeholder where we added controls dynamically in  the code behind. Now, the form is ready. I have to validate the form also, but we will discuss that in our next article. Here, we will just discuss the dynamic form creation.

So, our form is ready. Let's move to the next requirement, to read the data from these controls. Since we have created these controls dynamically, so we have to read the data from these controls in the same way. I created a new function to read the data from these fields. I tried to make this function as short and as dynamic as I could.  
  1. public void Save()  
  2.     {  
  3.         DataTable dtFormValues = new DataTable();  
  4.         dtFormValues.Columns.Add("FormId"typeof(Int32));  
  5.         dtFormValues.Columns.Add("FieldName"typeof(String));  
  6.         dtFormValues.Columns.Add("Value"typeof(String));  
  7.   
  8.         DataTable dt = new DataTable();  
  9.         dt = CustomFields();  
  10.         if (dt.Rows.Count > 0)  
  11.         {  
  12.             for (Int32 i = 0; i < dt.Rows.Count; i++)  
  13.             {  
  14.                 String FieldName = Convert.ToString(dt.Rows[i]["FieldName"]);  
  15.                 String FieldType = Convert.ToString(dt.Rows[i]["FieldType"]);  
  16.                 dtFormValues.NewRow();  
  17.   
  18.                 if (FieldType.ToLower().Trim() == "textbox")  
  19.                 {  
  20.                     TextBox txtbox = (TextBox)placeholder.FindControl("txt" + FieldName);  
  21.                     if (txtbox != null)  
  22.                     {  
  23.                         dtFormValues.Rows.Add(ClientId, FieldName, txtbox.Text);  
  24.                     }  
  25.                 }  
  26.                 else if (FieldType.ToLower().Trim() == "checkbox")  
  27.                 {  
  28.                     CheckBox checkbox = (CheckBox)placeholder.FindControl("chk" + FieldName);  
  29.                     if (checkbox != null)  
  30.                     {  
  31.                         dtFormValues.Rows.Add(ClientId, FieldName, checkbox.Checked ? "1" : "0");  
  32.                     }  
  33.                 }  
  34.                 else if (FieldType.ToLower().Trim() == "radiobutton")  
  35.                 {  
  36.                     RadioButtonList radiobuttonlist = (RadioButtonList)placeholder.FindControl("rbnlst" + FieldName);  
  37.                     if (radiobuttonlist != null)  
  38.                     {  
  39.                         dtFormValues.Rows.Add(ClientId, FieldName, radiobuttonlist.SelectedValue);  
  40.                     }  
  41.                 }  
  42.                 else if (FieldType.ToLower().Trim() == "dropdownlist")  
  43.                 {  
  44.                     DropDownList dropdownlist = (DropDownList)placeholder.FindControl("ddl" + FieldName);  
  45.                     if (dropdownlist != null)  
  46.                     {  
  47.                         dtFormValues.Rows.Add(ClientId, FieldName, dropdownlist.SelectedValue);  
  48.                     }  
  49.                 }  
  50.             }  
  51.         }  
  52.     } 
We created a function in which we call the same function where we have fieldname and fieldtype. Through that, we would find the control in the placeholder with the dynamic id, and create a data table. After finding the control, we added the data in this data table. Now, in this for loop, you can save this data table into your database. I haven't done it yet but will show you how the data I put in the form gets added in this data table. 

Form  filled



Then, hitting on the submit button will invoke the submit click event on server side in which we are calling the save method.

Save button event



Now, enable break point in this Save function and see after the for loop result in the data table if you get the correct data or not.



You can see in the above image, when we fill the form and hit the submit button, the values are stored in the data table. You can save these values into the database. I haven't saved the values in the database, just created the dynamic form to show you how we can get the values from these controls. That's it for now.

Up Next
    Ebook Download
    View all
    Learn
    View all