Sunday, September 19, 2010

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

This article discuss how to add row of controls to the page using add button click. To preserve the view state we add controls to the page in the page init method. Because there is no viewstate present in the init phase, we use hidden field and Request.Form object to get the value by the init phase. When you click enter in the last textbox of the row it add a new row using onkeyup javascript event. Clear button also works using a hidden filed where it keep all the deleted row indexes with in the range
Ps: this is the full version. - basic version of this post can be found here.
Example:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        function addNewRow(id, e) {
            var e = event || evt;
            var charCode = e.which || e.keyCode;
            if (charCode == 13) {                
                __doPostBack(id, '');
            }
        }
    </script>
    <script runat="server">
        int cols = 5;
        string btnClearId = "btnClear";
        string deletedRows = string.Empty;
        int numberOfRows = 0;
        public int NumberOfRows
        {
            get { return int.Parse(this.Request.Form[this.hdnRowCount.UniqueID] ?? "1"); }
            set { this.hdnRowCount.Value = value.ToString(); }
        }
        public string DeletedRows
        {
            get { return (this.Request.Form[this.hdnDeletedRows.UniqueID] ?? string.Empty).ToString(); }
            set { this.hdnDeletedRows.Value = value.ToString(); }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            string target = this.Request.Form.Get("__EVENTTARGET");
            if (!string.IsNullOrEmpty(target))
            {
                if (target.EndsWith(btnClearId))
                {
                    string index = target.Split('$').Last<string>().Replace(btnClearId, string.Empty);
                    if (string.IsNullOrEmpty(this.DeletedRows))
                        deletedRows = index;
                    else deletedRows = string.Format("{0},{1}"this.DeletedRows, index);
                    numberOfRows = this.NumberOfRows;
                }
                else if (target.Equals(this.btnAdd.UniqueID))
                {
                    numberOfRows = this.NumberOfRows + 1;
                    deletedRows = this.DeletedRows;
                }
            }
            else
            {
                deletedRows = this.DeletedRows;
                numberOfRows = this.NumberOfRows;
            }
            Table table = new Table();
            string[] dr = deletedRows.Split(',');
            for (int i = 0; i < numberOfRows; i++)
            {
                bool rowDeleted = false;
                if (!string.IsNullOrEmpty(deletedRows))
                    foreach (string d in dr) if (i == int.Parse(d)) rowDeleted = true;
                if (rowDeleted) continue;
                TableRow tr = new TableRow();
                for (int j = 0; j < cols; j++)
                {
                    TableCell td = new TableCell();
                    TextBox textBox = new TextBox() { ID = "Cell" + i + j };
                    if (j == this.cols - 1)
                        textBox.Attributes.Add("onkeyup"string.Format("javascript:addNewRow('{0}')",
                                this.btnAdd.UniqueID));
                    td.Controls.Add(textBox);
                    tr.Controls.Add(td);
                }
                TableCell cell = new TableCell();
                Button btnClear = new Button()
                {
                    Text = "Clear",
                    ID = i.ToString() + btnClearId,
                    CommandArgument = i.ToString(),
                    UseSubmitBehavior = false
                };
                cell.Controls.Add(btnClear);
                tr.Controls.Add(cell);
                table.Rows.Add(tr);
            }
            this.phCells.Controls.Add(table);
            if (this.NumberOfRows == 1) this.NumberOfRows = 2;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.DeletedRows = deletedRows;
            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="hdnRowCount" Value="1" />
        <asp:HiddenField runat="server" ID="hdnDeletedRows" />
    </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...