How to Display DataTable Data In To Html Table in Asp.net

How to Display DataTable Data In To Html Table in Asp.net

Introduction This Tutorial Explain How to Display the DataTable data into Html Table  without using the gridview. the data can be retrieve from the sql database.In this Project we can use visual Studio and Sqlserver database.

Here, In this First Step we can create sql database and add table as below "tbl_user


 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 fro the database.

using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace WebNav
{
    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;AttachDbFilename=C:\Users\home\Desktop\New folder (2)\WebNav\WebNav\App_Data\Database1.mdf;Integrated 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;
        }
    }
}

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.


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 WebNav
{
    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() });
}

The OutPut can be look like following.



Previous
Next Post »

1 comments:

Write comments
Anonymous
AUTHOR
20 November 2015 at 03:28 delete

nice working well.....

Reply
avatar