In ASP.NET C# we have Grid Views, Data Lists and so on for showing data but here we will create table at run time and we will show our data in that table.
The following is my SQL Server Data Table structure.
Image 1.
The following is the data in my table:
Image 2.
The following is my Aspx page is:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowData.aspx.cs" Inherits="DisplayDataInDynamicallyTable.ShowData" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Display Data in Dynamically Created Table</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <table style="width: 50%; text-align: center; background-color: skyblue;">
- <tr>
- <td align="center">
- <asp:PlaceHolder ID="DBDataPlaceHolder" runat="server"></asp:PlaceHolder>
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
The following is my Aspx.cs code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.Text;
-
- namespace DisplayDataInDynamicallyTable
- {
- public partial class ShowData : System.Web.UI.Page
- {
- SqlDataAdapter da;
- DataSet ds = new DataSet();
- StringBuilder htmlTable = new StringBuilder();
-
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- BindData();
- }
-
- private void BindData()
- {
- SqlConnection con = new SqlConnection();
- con.ConnectionString = @"Data Source=MYPC\SqlServer2k8;Integrated Security=true;Initial Catalog=MyCompany";
- SqlCommand cmd = new SqlCommand("SELECT * FROM Customer", con);
- da = new SqlDataAdapter(cmd);
- da.Fill(ds);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
-
- htmlTable.Append("<table border='1'>");
- htmlTable.Append("<tr style='background-color:green; color: White;'><th>Customer ID.</th><th>Name</th><th>Address</th><th>Contact No</th></tr>");
-
- if (!object.Equals(ds.Tables[0], null))
- {
- if (ds.Tables[0].Rows.Count > 0)
- {
-
- for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
- {
- htmlTable.Append("<tr style='color: White;'>");
- htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CustID"] + "</td>");
- htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Name"] + "</td>");
- htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Address"] + "</td>");
- htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["ContactNo"] + "</td>");
- htmlTable.Append("</tr>");
- }
- htmlTable.Append("</table>");
- DBDataPlaceHolder.Controls.Add(new Literal { Text = htmlTable.ToString() });
- }
- else
- {
- htmlTable.Append("<tr>");
- htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");
- htmlTable.Append("</tr>");
- }
- }
- }
- }
- }
Now run the application; it will look as in the following:
Image 3.