In this post i would like to gave you a brief idea about how to create dynamic controls and
how to handle them with events.



we can create dynamic controls by creating an object or an instance to that particular
control class. If we add those controls to a panel or to a table then those controls will be
loaded at run time.

First here you need to take include the following code in your default.aspx page so that you
can add the reaming controls dynamically.

In default.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="NumberOFfeildsAtATime" %>

<!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>Number Of Feilds Inerting at a time</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Label ID="lblRequest" runat="server"
            Text="Enter Number of feilds you want to enter:"></asp:Label>
        <asp:TextBox ID="txtNumber"
            runat="server" ValidationGroup="g1" Width="35px"></asp:TextBox>
&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="txtNumber" Display="Dynamic"
            ErrorMessage="Please enter Number of rows you want" 
ValidationGroup="g1"></asp:RequiredFieldValidator>
&nbsp;<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="txtNumber" Display="Dynamic"
            ErrorMessage="Please enter Only numbers" ValidationExpression="^\d+$"
            ValidationGroup="g1"></asp:RegularExpressionValidator>
        <asp:Button ID="btnCreate" runat="server" onclick="btnCreate_Click"
            Text="Create" ValidationGroup="g1" />
        <asp:Button ID="btnClear" runat="server" onclick="btnClear_Click" Text="Clear"
            Visible="False" />
        <br />
         <asp:Label ID="lblIndtotal" runat="server"
            Text=""></asp:Label>
            <asp:Label ID="lblAustotal" runat="server"
            Text=""></asp:Label>
        <br />
   
    </div>
    </form>
</body>
</html>

Now its the time to create a dynamic table and dynamic controls and events for each
control. For that here i created Instances for each control like TextBox, Label, Tabel,
TabelRow,.., After that based on the number of items count i just created different items
and i handled the click events for the button controls.,

Now just copy the below code in your default.aspx.cs file.

In default.aspx.cs:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class NumberOFfeildsAtATime : System.Web.UI.Page
{
    static Button btnSubmit = new Button();
    static Button btnReset = new Button();

    static Label lblSno = new Label();
    static Label lblScore = new Label();
    static Label lblScoreVs = new Label();
 
    static TextBox[] txtScore;
    static TextBox[] txtScorevs;

    RequiredFieldValidator[] RfvScore;
    static Table tblDynamic = new Table(); 
   
   

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            tblDynamic.Rows.Clear();
       
        form1.Controls.Add(tblDynamic);
        btnSubmit.Click += new EventHandler(this.btnSubmit_Click);
        btnReset.Click += new EventHandler(this.btnReset_Click); 
 
    }
    public void GenerateFeilds(int n)
    {       
        tblDynamic.Rows.Clear();
        txtScore = new TextBox[n];
        txtScorevs = new TextBox[n];
       
        RfvScore = new RequiredFieldValidator[n];

        TableRow[] tr = new TableRow[n + 3];
        TableCell[,] td = new TableCell[n + 3, 3];

        for (int r = 0; r < n + 3; r++)
            for (int i = 0; i < 3; i++)
                td[r, i] = new TableCell();


        tr[0] = new TableRow();

        lblSno.Text = "Overs";
        lblScore.Text = "Inds Score";
        lblScoreVs.Text = "Austs Score";

        td[0, 0].Controls.Add(lblSno);
        td[0, 1].Controls.Add(lblScore);
        td[0, 2].Controls.Add(lblScoreVs);

        for (int i = 0; i < 2; i++)
            tr[0].Cells.Add(td[0, i]);

        tblDynamic.Rows.Add(tr[0]);

        for (int r = 1; r < n + 1; r++)
        {
            txtScore[r - 1] = new TextBox();
            txtScorevs[r - 1] = new TextBox();
           
            RfvScore[r - 1] = new RequiredFieldValidator();

            txtScore[r - 1].ID = "txtScore" + r;
            txtScorevs[r - 1].ID = "txtScoreVs" + r;
            RfvScore[r - 1].ID = "RfvScores" + r;
            txtScore[r - 1].ValidationGroup = "g1";

            RfvScore[r - 1] = new RequiredFieldValidator();
            RfvScore[r - 1].ControlToValidate = txtScore[r - 1].ID;
            RfvScore[r - 1].ValidationGroup = "g1";
            RfvScore[r - 1].Text = "*";

            td[r, 0].Text = r.ToString();
            td[r, 1].Controls.Add(txtScore[r - 1]);
            td[r, 2].Controls.Add(txtScorevs[r - 1]);
            td[r, 1].Controls.Add(RfvScore[r - 1]);

            tr[r] = new TableRow();

            for (int i = 0; i < 3; i++)
                tr[r].Cells.Add(td[r, i]);

            tblDynamic.Rows.Add(tr[r]);
        }

        btnSubmit.Text = "Calculate Scores";
        btnReset.Text = "Reset";
        btnSubmit.ValidationGroup = "g1";


        tr[n + 1] = new TableRow();
        tr[n + 2] = new TableRow();
        td[n + 1, 0].Controls.Add(btnSubmit);
        td[n + 1, 1].Controls.Add(btnReset);
        tr[n + 1].Cells.Add(td[n + 1, 0]);
        tr[n + 1].Cells.Add(td[n + 1, 1]);
        tblDynamic.Rows.Add(tr[n + 1]);
        form1.Controls.Add(tblDynamic);
    }
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt16(txtNumber.Text) <= 0)
        {             
            Response.Write("<script>alert('Please enter Greterthan Zero values 
only')</script>");
        }
        else
        {
            btnCreate.Visible = false;
            txtNumber.Visible = false;
            btnClear.Visible = true;
            lblRequest.Visible = false;
            GenerateFeilds(Convert.ToInt16(txtNumber.Text));
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int indnum = 0;
        int ausnum = 0;
        for (int i = 0; i < txtScore.Length; i++)
        {
            indnum += Convert.ToInt32(txtScore[i].Text.ToString());
            ausnum += Convert.ToInt32(txtScorevs[i].Text.ToString());
        }
        lblIndtotal.Text = "Inds Total Score= " + indnum;
        lblAustotal.Text = "Aus Total Score= " + ausnum;
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        int n = tblDynamic.Rows.Count;
        for (int r = 0; r < n - 2; r++)
        {
            txtScore[r].Text = "";
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        tblDynamic.Rows.Clear();       
        form1.Controls.Add(tblDynamic);
        txtNumber.Visible = true;
        btnClear.Visible = false;
        btnCreate.Visible = true;
        lblRequest.Visible = true;
    }
   
   
}
Now build it and debug it. Then it will ask you to enter number fields you want to create dynamically.


You can download the Full Source code from here.

If you had any quires please let me know.

Share it

0 comments:

Post a Comment