Tuesday, October 28, 2014

HtmlTable DataTable loop

This simple code will help you to understand on how to loop through the DataTable in C# and showing the result in HtmlTable,HtmlTableRow and HtmlTableCell in C#


      var list = SPContext.Current.Web.Lists["Departments"];
            SPQuery query = new SPQuery();
            query.Query = "1";
            DataTable dt = list.GetItems(query).GetDataTable();

            HtmlTable table = new HtmlTable();
            HtmlTableRow hrow = null;
            HtmlTableCell cell = null;
            int index = 0;
            hrow = new HtmlTableRow();
            foreach (DataColumn col in dt.Columns)
            {
                cell = new HtmlTableCell();
                cell.InnerHtml = col.ColumnName;
                hrow.Cells.Add(cell);
                index++;

            }
            table.Rows.Add(hrow);
            foreach (DataRow drows in dt.Rows)
            {
                hrow = new HtmlTableRow();
                for (int hcol = 0; hcol < dt.Columns.Count; hcol++)
                {
                    cell = new HtmlTableCell();
                    cell.InnerHtml = drows[hcol].ToString();
                    hrow.Cells.Add(cell);

                }
                table.Rows.Add(hrow);
            }
            //--->Write logict to see
       
            tblSpace.Controls.Add(table);