Create an HTML button on runtime in Asp.net using C

How to create an HTML button on runtime in Asp.net using C#:

HTML button on runtime in Asp.net using C#:

Creating a button control by using the drop down functionality is very easy and simple. Also, adding its various properties include – text, style, width, height, weight, events are too simple. But, when the thing is about creating it dynamically. Most developers get nervous and confused. So, here we tried something that may help you out with this query.

 Html Button control dynamically steps by step.


Step-1: Create a New Empty Asp.net Web site. Add a Web Form (Html_Button_Display_Runtime.aspx).
Step-2: Press F7 on the web form. To write server side coding.
Step-3: This step is all about the creation of Html Button control dynamically.
Step-4: This step will tell us how to declare Text property of a button and also how to put CSS (i.e. styling) on Button Text.
Step-5: This step will tell us how to put CSS (i.e. styling) on Html Button.
Step-6: This step will tell us how to add a button click event handler.
            (I): Adding Button click Event Handler
            (II): Adding Button click Event Definition
Step-7: Last step is the most necessary step. This will add/bind the Html Button control on the Page.


Practical Implementation:

View code (Html_Button_Display_Runtime.aspx.cs)

using System;
using System.Web.UI.HtmlControls;

public partial class Html_Button_Display_Runtime : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        /*Step-3: Creating Html Button Control*/
        HtmlButton btn1 = new HtmlButton();

        /*Step-4: Applying CSS (i.e. styling) on Button Text*/
        btn1.InnerHtml = "<strong><font style='color: #808080; font-size:20px;'>Html Button Clicked</font></strong>";   /*----> Changing style for text*/

        /*Step-5: Changing style on Html Button control*/
        btn1.Style.Add("background-color""black");
        btn1.Style.Add("font-weight""bold");
        btn1.Style.Add("color""white");
        btn1.Style.Add("width""150px");
        btn1.Style.Add("height""60px");

        /*Step-6(I): Adding Button click Event Handler*/
        btn1.ServerClick+=new EventHandler(btn1_ServerClick);

        /*Step-7: Adding Html Button control to Page*/
        Page.Controls.Add(btn1);               
    }

    /*Step-6(II): Adding Button click Definition*/
    protected void btn1_ServerClick(object sender, EventArgs e)
    {
        Response.Write("<script>alert('Button pressed!')</script>");
    }
}

Debug (CTRL+SHIFT+B) or (F6) the code to check for any compile time error. If not, run the Application by pressing (CTRL+F5). You’ll get your output like this



Related Post of Asp.net And Html :

Comments

Popular posts from this blog