Tuesday, April 13, 2010

Runtime Add Dynamic Button And Handle Click Event in ASP.NET C# VB.NET




Please visit my new Web Site https://coderstechzone.com



In most of the cases developers need to add dynamic controls in asp.net application using code behind or runtime. Here in this article i will explain how one can add dynamic Asp.Net Server side Button in runtime and assign or handle click event in asp.net using C# and VB.NET.

To add a asp.net server side button control when page is loaded. We need to write the below code segment under page_Load Event:









C#.Net:
protected void Page_Load(object sender, EventArgs e)
    {
        Button cmd = new Button();
        cmd.Text = "Click Me";
        this.form1.Controls.Add(cmd);
        cmd.Click += new EventHandler(Dynamic_Method);
    }

    protected void Dynamic_Method(object sender, EventArgs e)
    {
        Response.Write("You have clicked at: "+DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
    }

VB.Net:
Private Sub Dynamic_Method(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Response.Write("You have clicked at: " + DateTime.Now)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cmd As New Button
        cmd.ID = "BOTON"
        cmd.Text = "Click Me"
        AddHandler cmd.Click, AddressOf Dynamic_Method
        Form.Controls.Add(cmd)
    End Sub

1 comments:

Loosie said...

Thanks!
Please let me know how to determine which button was clicked. I would like to insert the record key into CommandArgument of button. When it is clicked I would like to retrieve it. then use to edit or delete record.

Thanks
Adrian DD Sigamoney

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash