create dynamic table in c#

Hello Everyone,

I'm going to share the code sample for create dynamic table using c#.

Today, i have a requirement to create a dynamic table with the help of user inputs( number of rows and columns) on click on create table button.

These look like the below:

In the 1st step

I'm going to share the code sample for .aspx page

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        No. of Rows: <asp:TextBox ID="txt_TableRows" runat="server" Width="65px" />&nbsp;
        No. of Cols: <asp:TextBox ID="txt_TableCols" runat="server" Width="65px" /> <br />

        <asp:CheckBox ID="chk_CellBorder" runat="server" Text="Broder of cells" />&nbsp;
        <asp:Button ID="btn_createTable" CssClass="btnColor" OnClick="btn_createTable_Click" runat="server" Text="Create Table" />
        <asp:Table ID="tblTable" runat="server" />

In the 2nd step

I'm going to share the code sample for .cs page

namespace Create_dynamic_table
    public partial class _Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            //Add to border style.
            tblTable.BorderStyle = BorderStyle.Inset;
            tblTable.BorderWidth = Unit.Pixel(2);

        /// <summary>
        /// button event for create table
        /// </summary>
        protected void btn_createTable_Click(object sender, System.EventArgs e)
            //Input row and column.
            int RowNo = Int32.Parse(txt_TableRows.Text);
            int ColsNo = Int32.Parse(txt_TableCols.Text);

            //Clear table.

            if (RowNo > 0 && ColsNo > 0)
                //Used for creat row.
                for (int i = 0; i < RowNo; i++)
                    TableRow Rows = new TableRow();

                    //Used for creat cells.
                    for (int j = 0; j < ColsNo; j++)
                        TableCell cells = new TableCell();
                        Label lbl = new Label();
                        lbl.Text = "[" + i.ToString() + "," + j.ToString() + "]<br />";

                        if (chk_CellBorder.Checked == true)
                            cells.BorderStyle = BorderStyle.Inset;
                            cells.BorderWidth = Unit.Pixel(2);

            else {
                Response.Write("Please enter no. of rows and cols");


Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
Post a Comment Powered by Blogger.
ASK Questions