Friday, December 2, 2011

how to create dynamic table in asp.net


How to create dynamic table in asp.net 3.5
Why the LoadViewState()?
When the controls are added to page, it is done quiet early in the page event cycle. Hence the LoadViewState() gives you an ideal placeholder to recreate the controls. Since the LoadViewState() method is called before the Page_Load() event, re-adding controls in this method assures that the controls can be access and manipulated by the time any event occurs on them.
Step 1: Create a new ASP.NET application. Add two textboxes (txtRows and txtCols) and a button (btnGenerate) control to the page. The two textboxes will accept the number of Rows and Columns from the user. Based on the input in the textboxes, the table will be created dynamically on the button click. Also add a container element (to position the table) and a button (btnPost) to cause a postback the second time, once the table data is manipulated.
The mark up will look similar to the following:
<body>
    <form id="form1" runat="server">
    <div>
    <div>
        Rows: <asp:TextBox ID="txtRows" runat="server" Width="30px"> </asp:TextBox> <br />
        Cols: &nbsp;<asp:TextBox ID="txtCols" runat="server" Width="30px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnGenerate" OnClick="btnGenerate_Click" runat="server" Text="Generate" />&nbsp;<br /> <br />
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <br />
        <br />
    </div>
    </div>
        <asp:Button ID="btnPost" runat="server" OnClick="Button1_Click" Text="Cause Postback" />
    </form>
</body>

Step 2: The number of rows and columns for the table is to be taken from the user. For this purpose, we will accept the values in the Page_Load() event. We will create properties for both the rows and columns and store in the ViewState so that the data is available on the postback.
C#
// Rows property to hold the Rows in the ViewState
    protected int Rows
    {
        get
        {

           return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
        }
        set
        {
            ViewState["Rows"] = value;
        }
    }

    // Columns property to hold the Columns in the ViewState
    protected int Columns
    {
        get
        {
          return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
        }
        set
        {
            ViewState["Columns"] = value;
        }
    }
protected void Page_Load(object sender, EventArgs e)
    {
        // Run only once a postback has occured
        if (Page.IsPostBack)
        {
            //Set the Rows and Columns property with the value
            //entered by the user in the respective textboxes
            this.Rows = Int32.Parse(txtRows.Text);
            this.Columns = Int32.Parse(txtCols.Text);
        }

        CreateDynamicTable();
    }
VB.NET
' Rows property to hold the Rows in the ViewState
      Protected Property Rows() As Integer
            Get
                  If Not ViewState("Rows") Is Nothing Then
                        Return CInt(Fix(ViewState("Rows")))
                  Else
                        Return 0
                  End If
            End Get
            Set(ByVal value As Integer)
                  ViewState("Rows") = value
            End Set
      End Property

      ' Columns property to hold the Columns in the ViewState
      Protected Property Columns() As Integer
            Get
             If Not ViewState("Columns") Is Nothing Then
                   Return CInt(Fix(ViewState("Columns")))
             Else
                   Return 0
             End If
            End Get
            Set(ByVal value As Integer)
                  ViewState("Columns") = value
            End Set
      End Property

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            ' Run only once a postback has occured
            If Page.IsPostBack Then
                  'Set the Rows and Columns property with the value
                  'entered by the user in the respective textboxes
                  Me.Rows = Int32.Parse(txtRows.Text)
                  Me.Columns = Int32.Parse(txtCols.Text)
            End If
            CreateDynamicTable()


End Sub
Observe over here that the values of the Rows and Columns properties are set only after the user enters the values and clicks the button, which causes the postback. That is the reason why we are checking against the If(Page.IsPostBack).
Step 3: On the button click, create the dynamic table as shown below. The code has been commented to help you understand.
C#
protected void btnGenerate_Click(object sender, EventArgs e)
    {
        CreateDynamicTable();
    }


    private void CreateDynamicTable()
    {
        PlaceHolder1.Controls.Clear();

        // Fetch the number of Rows and Columns for the table 
        // using the properties
        int tblRows = Rows;
        int tblCols = Columns;
        // Create a Table and set its properties 
        Table tbl = new Table();
        // Add the table to the placeholder control
        PlaceHolder1.Controls.Add(tbl);
        // Now iterate through the table and add your controls 
        for (int i = 0; i < tblRows; i++)
        {
            TableRow tr = new TableRow();
            for (int j = 0; j < tblCols; j++)
            {
                TableCell tc = new TableCell();
                TextBox txtBox = new TextBox();
                txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
                // Add the control to the TableCell
                tc.Controls.Add(txtBox);
                // Add the TableCell to the TableRow
                tr.Cells.Add(tc);
            }
            // Add the TableRow to the Table
            tbl.Rows.Add(tr);
        }

       // This parameter helps determine in the LoadViewState event,
       // whether to recreate the dynamic controls or not

       ViewState["dynamictable"] = true;
    }

VB.NET
Protected Sub btnGenerate_Click(ByVal sender As Object, ByVal e As EventArgs)
            CreateDynamicTable()
End Sub


      Private Sub CreateDynamicTable()
            PlaceHolder1.Controls.Clear()

            ' Fetch the number of Rows and Columns for the table 
            ' using the properties
            Dim tblRows As Integer = Rows
            Dim tblCols As Integer = Columns
            ' Create a Table and set its properties 
            Dim tbl As Table = New Table()
            ' Add the table to the placeholder control
            PlaceHolder1.Controls.Add(tbl)
            ' Now iterate through the table and add your controls 
            For i As Integer = 0 To tblRows - 1
                  Dim tr As TableRow = New TableRow()
                  For j As Integer = 0 To tblCols - 1
                        Dim tc As TableCell = New TableCell()
                        Dim txtBox As TextBox = New TextBox()
                        txtBox.Text = "RowNo:" & i & " " & "ColumnNo:" & " " & j
                        ' Add the control to the TableCell
                        tc.Controls.Add(txtBox)
                        ' Add the TableCell to the TableRow
                        tr.Cells.Add(tc)
                  Next j
                  ' Add the TableRow to the Table
                  tbl.Rows.Add(tr)
            Next i

         ' This parameter helps determine in the LoadViewState event,
         ' whether to recreate the dynamic controls or not

         ViewState("dynamictable") = True
      End Sub

Step 4: The last piece of code is to determine whether to recreate the controls based on the ViewState[“dynamictable”]. Here’s how it works. The first time the page loads, the  LoadViewState() does not execute. The ViewState[“dynamictable”] flag is initialized once the button click occurs. When the postback occurs on the second button click (btnPost), it is then that our code written for overriding the LoadViewState() runs. The base.LoadViewState() instantiates the ViewState object. We then check the value of our ViewState flag, and based on the result, re-create our Table.
C#
    // Check the ViewState flag to determine whether to
    // rebuild your table again
    protected override void LoadViewState(object earlierState)
    {
        base.LoadViewState(earlierState);
        if (ViewState["dynamictable"] == null)
            CreateDynamicTable();
    }
VB.NET
' Check the ViewState flag to determine whether to
      ' rebuild your table again
      Protected Overrides Sub LoadViewState(ByVal earlierState As Object)
            MyBase.LoadViewState(earlierState)
            If ViewState("dynamictable") Is Nothing Then
                  CreateDynamicTable()
            End If
      End Sub
That’s it. Run the code. Enter the number of Rows and Columns to be created and click the Generate button to create the table. Since the table contains textboxes in each cell, manipulate the text inside the table and hit the ‘Cause Postback’ button. Even after the postback, the values of the table control are retained.
Note: If multiple controls of the same type are created, remember to create them with the same ID's.
I hope you now have a good idea now of how to create controls dynamically. You can adopt a similar approach to create any dynamic control in your application. I hope the article was useful and I thank you for viewing it.

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...