Thursday, June 24, 2010

How to dynamically add a row of controls using add button : Asp.net - Part 1: The Simple Version

Demo:
This example demonstrate how to add controls to asp.net page using add button using a hidden field. However because there is no viewsate present in the page init method, we have to use request form collection to access the row count
If you need a full version of this example including clearbutton and enter button key press to add new row, please see this artilce.
Ps: this is the basic version - full version is available here.
Example:
<%@ Page Language="C#"%>
<html>
<head id="Head1" runat="server">
     <script runat="server">
        int cols = 4;
        int numberOfRows = 0;
        public int NumberOfRows
        {
            get { return int.Parse(this.Request.Form[this.htnRowCount.UniqueID] ?? "1"); }
            set { this.htnRowCount.Value = value.ToString(); }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Table table = new Table();
            string target = this.Request.Form.Get("__EVENTTARGET");
            if (string.IsNullOrEmpty(target))
                numberOfRows=1;
            else
            {
                if (target.Equals(this.btnAdd.UniqueID))
                    numberOfRows = this.NumberOfRows + 1;
            }
            for (int i = 0; i < numberOfRows; i++)
            {
                TableRow tr = new TableRow();
                for (int j = 0; j < cols; j++)
                {
                    TableCell td = new TableCell();
                    td.Controls.Add(new TextBox() { ID = "Cell" + i + j });
                    tr.Controls.Add(td);
                }
                table.Rows.Add(tr);
            }
            this.phCells.Controls.Add(table);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.NumberOfRows = numberOfRows;
        }       
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="phCells"></asp:PlaceHolder>
        <asp:Button runat="server" ID="btnAdd" Text="Add" UseSubmitBehavior="false" />
        <asp:HiddenField runat="server" ID="htnRowCount" Value="1" />
    </form>
</body>
</html>

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...