This is not a correct a way to show the HTML Table in web page using repeated line of Response.Write.
Use the StringBuilder, Add the html code and assign it to some Panel or Div tag.
Please refer this code.
HTML
<form id="form1" runat="server">
<asp:PlaceHolder ID = "PlaceHolder1" runat="server" />
</form>
Namespaces
using System.Data;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//Populating a DataTable from database.
this.GetData();
}
}
private void GetData()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers"))
{
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
//Building an HTML string.
StringBuilder html = new StringBuilder();
//Table start.
html.Append("<table border = '1'>");
html.Append("<table>");
int index = 1;
while (sdr.Read())
{
if (index == 1)
{
html.Append("<tr>");
for (int i = 0; i < sdr.FieldCount; i++)
{
html.Append("<td>");
html.Append(sdr.GetName(i));
html.Append("</td>");
}
html.Append("</tr>");
}
index++;
html.Append("<tr>");
for (int i = 0; i < sdr.FieldCount; i++)
{
html.Append("<td>");
html.Append(sdr.GetValue(i));
html.Append("</td>");
}
html.Append("</tr>");
}
html.Append("</table>");
//Table end.
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
con.Close();
}
}
}
Screenshots
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download database SQL from here.