Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamically Add .net controls to Web Form on Button click event
#1
Star 
Hi Guys, This article regards to Dynamically create asp.net controls in Web application
Here I used One Button control and Panel. Button having Click event that does code behind activity to Create asp.net controls and Adds to Panel.
Thus we can add any number of controls to page. Here I'm adding Textbox Control to Page i.e. Inside Panel .
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
   
       <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
       <asp:Panel ID="Panel1" runat="server">
       </asp:Panel>
   
   </div>
   </form>
</body>
</html>
Code:
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
   public partial class Test : System.Web.UI.Page
   {
       static int i = 0;
       TextBox txt = new TextBox();
       protected void Page_Load(object sender, EventArgs e)
       {

       }

       protected void Button1_Click(object sender, EventArgs e)
       {
           i++;
           for (int j = 0; j < i; j++)
           {
               txt = new TextBox();
               txt.ID = j.ToString();
               Panel1.Controls.Add(txt);
           }
       }
   }
}

Here the main Logic is: 
Code:
//Create New Textbox
 TextBox txt = new TextBox();
 txt.ID = "test" + ID;
 txt.Text = "";

//Newly created textbox add to Panel
 Panel1.Controls.Add(txt);
Thank U, Hope it helps...
Here I'm attaching Source code file...


Attached Files
.zip   Test.zip (Size: 17.4 KB / Downloads: 1)
Reply
#2
Thanks very much nagaraj this was very helpful.
Reply
#3
Hi Alexander,

Please share if you find it helpful, using the share at the bottom of every page.

Thank You..
Reply


Possibly Related Threads...
Thread Author Replies Views Last Post
  How to Bind Repeater dynamically from database using Datatable in ASP.NET? ChannuShahapur 2 1, 846 04-07-2016, 10:30 AM
Last Post: Mahesh
  Radio button Tutorial for beginners of ASP.NET ChannuShahapur 0 758 21-11-2015, 02:47 PM
Last Post: ChannuShahapur
  How Do I Display window form application in windows service? Santosh Kokatnur 5 5, 695 30-10-2015, 02:53 PM
Last Post: Santosh Kokatnur
  Display the console application data in the windows form using c# Santosh Kokatnur 0 2, 251 12-10-2015, 02:55 PM
Last Post: Santosh Kokatnur

Forum Jump:


Users browsing this thread: 1 Guest(s)