-->

How to add dynamic control and manage server side events in ASP.NET

Introduction

In this post I am explain How to add dynamic control and manage server side events in ASP.NET

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Webpage and Design for show dynamically generated controls.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
  1. <h3>Dynamic Control Add & Fire Server Side Events</h3>
  2. <div style="background-color: #CCFFCC">
  3. <%-- This Label added for show message after click button which are dinamically created --%>
  4. <asp:Label ID="lblMessage" runat="server" Text="No Button Clicked!" Font-Bold="True" Font-Size="20pt"></asp:Label>
  5. <%-- Panel will contain dynamically generated buttons --%>
  6. <asp:Panel ID="pnlButtonContainer" runat="server"></asp:Panel>
  7. </div>

Step-3: Write function for Create & render server control into webpage.


  1. private void AddButtons(int noOfButton)
  2. {
  3. for (int i = 0; i < noOfButton; i++)
  4. {
  5. Button b = new Button();
  6. b.ID = "Button" + (i+1);
  7. b.Text = "Button" + (i + 1);
  8. // This below line added for find out which button is clicked
  9. b.CommandArgument = "Button" + (i + 1);
  10. // generate Click event
  11. b.Click += new EventHandler(this.ButtonClick);
  12.  
  13. // this line will add control in Panel (render control in page)
  14. pnlButtonContainer.Controls.Add(b);
  15.  
  16. }
  17. }
  18. protected void ButtonClick(object sender, EventArgs e)
  19. {
  20. lblMessage.Text = ((Button)sender).CommandArgument + " Clicked";
  21. }

Step-4: Write code in page load event for call function which is responsible for create dynamic control

Here you will notice that, I have called function which is responsible for create dynamic control in page load event. This will create control eachtime page is loaded. Other wise we have to face a common problem "dynamically generated controls disappear postback".

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. // Here call function for create dynamic control
  4. AddButtons(5);
  5. // this function is required to call for each postback because no view state is stored when generate
  6. // dynamic control
  7.  
  8. }

Step-5: Run application.




Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: