Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here i have retrieved a datatable from database now i have nine td's on my webpage i want to bind
first datarow to first td, second datarow to second td and so on pls tell me which loop i have to follow in order to achieve this so that i can make my website dynamic
Posted

Try like this..

ASPX
XML
<table id="table1" runat="server" border="1" cellpadding="1" cellspacing="1">
   </table>


Code behind:
C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();  //start: creating dynamic datatable ( hardcoded)
                for (int i = 0; i < 9; i++)
                    dt.Columns.Add("column" + i);
                for (int i = 0; i < 10; i++)
                    dt.Rows.Add(1, 2, 3, 4, 5, 6, 7, 8, 9); //End: creating dynamic datatable ( hardcoded)

                CreateTable(dt, table1); // pass your datatable, and table name 

            }

        }

        private void CreateTable(DataTable dt, HtmlTable table)
        {
            HtmlTableRow rowheader = new HtmlTableRow();
            for (int j = 0; j < dt.Columns.Count; j++)
                rowheader.Cells.Add(new HtmlTableCell() { InnerText = dt.Columns[j].ColumnName });
            table.Rows.Add(rowheader);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                HtmlTableRow row = new HtmlTableRow();
                for (int j = 0; j < dt.Columns.Count; j++)
                    row.Cells.Add(new HtmlTableCell() { InnerText = dt.Rows[i][j].ToString() });
                table.Rows.Add(row);
            }
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900