Page

Display Data in HTML Table from Database using Asp.net in C#

// Example.aspx //

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Example.aspx.cs" Inherits="_Example" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
<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>


// Example.aspx.cs //

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.UI.WebControls;

public partial class Example : System.Web.UI.Page
{

SqlConnection scon = new SqlConnection("Your 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 Information";
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["ID"]+ "</td>");
htmlTable.Append("<td>" + articleReader["Name"] + "</td>");
htmlTable.Append("<td>" + articleReader["Mobno"] + "</td>");
htmlTable.Append("<td>" + articleReader["EmailId"] + "</td>");
htmlTable.Append("</tr>");
}
htmlTable.Append("</table>");

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

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

// SQL Table //






No comments:

Post a Comment