Display DataTable in HTML Table in ASP.Net using C#

Display DataTable in HTML Table in ASP.Net using C#

Introduction

In this tutorial we have learn how to Display DataTable in HTML Table in ASP.Net using C# without using gridview control. the data can be retrieve from the sql database and binds this data to html table.In this Project we can use visual Studio and Sql server database.

Step 1 : Here, In this First Step we can create sql database and add sql table with name “tbl_user

Step 2 : After Creating the database we can add new class and give name Dal.cs  In this class we can write the the Sql Query logic to fetch the data from the database.

public class DAL
{

public int id { get; set; }

public string name { get; set; }

public string city { get; set; }

SqlConnection con = new SqlConnection(@”Data Source=.\SQLEXPRESS;Security=True;User Instance=True”);

public DataTable Grid_data()
{
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(“select * from tbl_user”, con);
adp.Fill(dt);
return dt;
}
}

Step 3: Now You can add the Webform and need to add the code in the CodeBehind file as following. Here Datatable can be used to retrive the data from the dataBase and it can be display in Html table using the StringBuilder html tag can be append and display data.

public partial class GridRow : System.Web.UI.Page
{
DAL da = new DAL();
protected void Page_Load(object sender, EventArgs e)
{
// gridd();

DataTable dt =da.Grid_data();
StringBuilder html = new StringBuilder();
html.Append(“<table border = ‘1’ cellpadding=4 cellspacing=0>”);
html.Append(“<tr style=’background-color:green; color: White;’><th> ID</th><th>Name</th><th>City</th></tr>”);

foreach (DataRow row in dt.Rows)
{
html.Append(“<tr>”);
foreach (DataColumn column in dt.Columns)
{
html.Append(“<td>”);
html.Append(row[column.ColumnName]);
html.Append(“</td>”);
}
html.Append(“</tr>”);
}
html.Append(“</table>”);
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
}

Now Run your project and see output:

Display DataTable in HTML Table in ASP.Net using C#

SEE MORE

Leave a Reply

Your email address will not be published. Required fields are marked *