Display Data in HTML Table from Database using Asp.net

Display Data in HTML Table from Database using Asp.net:




HTML Table from Database using Asp.net:

In this post we describe how to print data from data base in to html page by C# code.


Code in html page for display data:



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Display Data from Database in HTML Table in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>



Now open code behind file C# code:



SqlConnection scon = new SqlConnection("<connection string>");
StringBuilder htmlTable = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM Emp";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();

htmlTable.Append("<table border='1'>");
htmlTable.Append("<tr><th>SlNo.</th><th>Name</th><th>Mobile Number</th><th>EmailId</th></tr>");

if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlTable.Append("<tr>");
htmlTable.Append("<td>" + articleReader["EMPID"]+ "</td>");
htmlTable.Append("<td>" + articleReader["EMPName"] + "</td>");
htmlTable.Append("<td>" + articleReader["EMPMobno"] + "</td>");
htmlTable.Append("<td>" + articleReader["EMPEmailId"] + "</td>");
htmlTable.Append("</tr>");
}
htmlTable.Append("</table>");

PlaceHolder1.Controls.Add(new Literal { Text = htmlTable.ToString() });

articleReader.Close();
articleReader.Dispose();
}
}
}

Comments