I've make a generic function PopulateTable(Table tblObj, DataTable dtObject, TableRow trHeader), if needed you can edit according to your needs, because some data may need certain formatting in table. The code itself easy to understand
- protected void Page_Load(object sender, EventArgs e)
- {
- //Assuming we have data in this tbl
- DataTable tbl = new DataTable();
- PopulateTable(tblContent, tbl, GetDocumentTableHeader());
- }
- private TableHeaderRow GetDocumentTableHeader()
- {
- TableHeaderRow thr = new TableHeaderRow();
- TableHeaderCell thc = new TableHeaderCell();
- thc.Text = "Title"; thc.CssClass = "title"; thr.Cells.Add(thc);
- thc = new TableHeaderCell();
- thc.Text = "Author"; thc.CssClass = "author"; thr.Cells.Add(thc);
- thc = new TableHeaderCell();
- thc.Text = "Description"; thc.CssClass = "categories"; thr.Cells.Add(thc);
- return thr;
- }
- private void PopulateTable(Table tblObj, DataTable dtObject, TableRow trHeader)
- {
- tblObj.Rows.Clear();
- tblObj.Rows.Add(trHeader);
- if (dtObject == null || dtObject.Rows.Count == 0)
- {
- //If no records found in DataTable then show No Result Found
- TableRow row = new TableRow();
- TableCell cell = new TableCell();
- cell.Text = "No Result Found!";
- cell.HorizontalAlign = HorizontalAlign.Center;
- cell.Font.Bold = true;
- cell.ForeColor = System.Drawing.Color.Red;
- cell.ColumnSpan = trHeader.Cells.Count;
- row.Cells.Add(cell);
- tblObj.Rows.Add(row);
- }
- else
- {
- for (int i = 0; i < dtObject.Rows.Count; i++)
- {
- TableRow row = new TableRow();
- for (int j = 0; j < trHeader.Cells.Count; i++)
- {
- TableCell cell = new TableCell();
- cell.Text = dtObject.Rows[i][j].ToString();
- row.Cells.Add(cell);
- }
- tblObj.Rows.Add(row);
- }
- }
- }
No comments:
Post a Comment