Sunday, December 16, 2012

creating multiple buttons dynamically and handling events in asp.net using C#

Previously i had shown
Now i will show how to create Multiple Buttons Dynamically & handle their Click events as shown

OutPut :



<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="Dynamic_Buttons._Default" %>
 
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <p>
        <asp:Label ID="Label1" runat="server" Text=" "></asp:Label>
        <asp:Panel ID="pnlButtons" runat="server">
        </asp:Panel>
    </p>
</asp:Content> 
 
Code Behind Page :
  
using System;
using System.Web.UI.WebControls;
using System.Drawing;
 
namespace Dynamic_Buttons
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                Button btn = new Button();
                btn.ID = "btn" + i;
                btn.Text = "Button " + i;
                btn.Click += new EventHandler(btn_Click);
 
                pnlButtons.Controls.Add(btn);
                Label lbl = new Label();
                lbl.ID = "lbl" + i;
                lbl.Text = "<br/>";
                pnlButtons.Controls.Add(lbl);
                btn.Visible = true;                
            }
        }
 
        void btn_Click(object sender, EventArgs e)
        {
            Button btnEvent = (Button)sender;
            //Write Conditions based on buttonClick
            string val = btnEvent.ID;  
            btnEvent.ForeColor = Color.Green;
            Label1.Text = "U clicked on " + btnEvent.Text + " .";
            //Response.Write(@"<script language='javascript'>alert('U clicked on " + btnEvent.Text + " .');</script>");
        }
    }
}


No comments:

Post a Comment