3

I am writing an ASP.NET page which reads data from a database and needs to show it in an HTML table. I don't want to use a gridView.

Here is the code I tried using c#:

    protected void Page_Load(object sender, EventArgs e)
    {
    DataTable dt = new DataTable();
        List<UserDetails> details = new List<UserDetails>();

        using (SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=Sample;Trusted_Connection=True;"))
        {
            using (SqlCommand cmd = new SqlCommand("select TOP 10 ImageFile,ProductName,Features from Product_category", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    UserDetails user = new UserDetails();
                    user.UserId = dtrow["ImageFile"].ToString();
                    user.UserName = dtrow["ProductName"].ToString();
                    user.Location = dtrow["Features"].ToString();
                    details.Add(user);
                }
            }
        }
        return details.ToArray();
    }
    public class UserDetails
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string Location { get; set; }
    }

Here is my html code:

<table id="tbDetails" width="800" runat="server">
<tbody>
<tr><td><table><tr><td></td></tr><tr><td></td></tr></table></td><td><table><tr><td></td></tr></table></td></tr>
</tbody>
</table>
2
  • 1
    Either you have to create table at code behind OR Bind existing table through AJAX call. Commented Oct 26, 2013 at 4:52
  • Possible duplicate of Show data in ASP.NET html table Commented Apr 6, 2016 at 14:46

4 Answers 4

12

First of all place your code in one private method that returns a string. The method:

public string getWhileLoopData()
{
 string htmlStr = "";
SqlConnection thisConnection = new SqlConnection(dbConnection);
        SqlCommand thisCommand = thisConnection.CreateCommand();
        thisCommand.CommandText = "SELECT * from Test";
        thisConnection.Open();
        SqlDataReader reader = thisCommand.ExecuteReader();

        while (reader.Read())
        {
            int id = reader.GetInt32(0);
            string Name = reader.GetString(1);
            string Pass = reader.GetString(2);
            htmlStr +="<tr><td>"+id+"</td><td>"+Name+"</td><td>"+Pass+"</td></tr>"                   
        }

        thisConnection.Close();
        return htmlStr;
}

Than you can use the this code:

<%=getWhileLoopData()%> tag in ASP.NET that is equal to <%Response.Write(getWhileData())%>

It should look something like this:

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/test.master" CodeFile="test.aspx.cs" Inherits="test" %>

<asp:Content ID="BodyContent" runat="server"  ContentPlaceHolderID="ContentPlaceHolder">
    <table width="100%" align="center" cellpadding="2" cellspacing="2" border="0" bgcolor="#EAEAEA" >
        <tr align="left" style="background-color:#004080;color:White;" >
            <td> ID </td>                        
            <td> Name </td>            
            <td>Pass</td>                        
        </tr>

        <%=getWhileLoopData()%>

    </table>
</asp:Content>

There is also the option to use an repeater control and bind the data from your DB to an Item Template

Sign up to request clarification or add additional context in comments.

3 Comments

I found the following error in the line string Name = reader.GetString(1); 'Data is Null. This method or property cannot be called on Null values.'
Check and debug your code whether data exists or not.. as this is working for me..
@Monika great solution and question + for both. Well I have a table like this with total and another table/gridview. When the other table's each cell is updated (in line), how can I recalculate this table?
2

If you want to go through the ajax call you can just refer your suitable version of jquery. Write webmethod at code behind. Call it from Ajax and bind the list details to the table. Bellow is the code.

Web Method in default.aspx.cs

 [WebMethod]
    public static List<UserDetails> GetDetails()
    {
        //Write your database logic here and add items in list
        List<UserDetails> details = new List<UserDetails>();
        details.Add(new UserDetails() { Location="aaaa", UserId="adv", UserName="fdfds"  });
        details.Add(new UserDetails() { Location = "bbbb", UserId = "hhhh", UserName = "aaaafds" });
        return details;
    }

Jquery AJAX call in aspx

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function () {
     var row = "";
     $.ajax({
         type: "POST",
         url: "Default.aspx/GetDetails",
         data: "{}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $.each(msg.d, function (index, obj) {
                 row += "<tr><td>" + obj.UserId + "</td><td>" + obj.UserName + "</td><td>" + obj.Location + "</td></tr>";
             });

             $("#tbDetails tbody").append(row);
         }
   });
 });
</script>

    <table id="tbDetails" width="800" runat="server" clientidmode="Static">
   <tbody>
    <tr><td>Userid</td><td>UserName</td><td>Location</td></tr>
    </tbody>
    </table>

Hope this helps you.

Comments

1
      public string wogrid()
        {
        string htmlStr = "";
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandText = "SELECT * from employees";
    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        int empID = reader.GetInt32(0);
        string empName = reader.GetString(1);
        int age = reader.GetInt32(2);
        string location = reader.GetString(3);
        int salary = reader.GetInt32(4);
        htmlStr += "<tr><td>" + empID + "</td>" + "<td>" + empName + "</td>" + "<td>" + age + "</td>" + "<td>" + location + "</td>" + "<td>" + salary + "</td></tr>";                
    }

    con.Close();
    return htmlStr;
    }

}

        /*****source code must me like ******/


        <table width="100%" align="center" cellpadding="2" cellspacing="2" border="0"    bgcolor="#EAEAEA" >
        <tr align="center" style="background-color:#004080;color:White;" >
        <td width="20%"> empID </td>                        
        <td width="20%"> empName </td>            
        <td width="20%">age</td>  
        <td width="20%">location</td>
        <td width="20%">salary</td>                      
      ![enter image description here][1]   </tr>

    <%=wogrid()%>

</table>

1 Comment

Little description would have helped a lot.
1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TYPES;
using BLLFactory;
using BOFactory;
using DALFactory;

namespace WebApplication5
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            IFSBLL fsv = BLLFactory.FSBLLF.ViewList();
            List<IFSBO> des = fsv.viewallListBLL();

            GridView2.DataSource = fsv;
            GridView2.DataBind();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {

        }

    }
}
--------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TYPES;
using BLLFactory;
using DALFactory;
using BOFactory;

namespace WebApplication5
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                viewdata();
            }
        }
        private void viewdata()
        {
            List<IFSBO> fs = DALFactory.FSDALF.viewallListBO();
            GridView1.DataSource = fs;
            GridView1.DataBind();
        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow SelectedRow = GridView1.Rows[e.RowIndex];
            Label fsid = (Label)SelectedRow.FindControl("Label1") as Label;

            DateTime depdt = Convert.ToDateTime((SelectedRow.FindControl("TextBox5") as TextBox).Text);
             DateTime desdt = Convert.ToDateTime((SelectedRow.FindControl("TextBox6") as TextBox).Text);
             int pcf = Convert.ToInt32((SelectedRow.FindControl("TextBox7") as TextBox).Text);
             int fcf = Convert.ToInt32((SelectedRow.FindControl("TextBox8") as TextBox).Text);
             int ecf = Convert.ToInt32((SelectedRow.FindControl("TextBox9") as TextBox).Text);





             int id = int.Parse(fsid.Text);
             DateTime depdt1 = Convert.ToDateTime(depdt);
             DateTime desdt1 = Convert.ToDateTime(desdt);
             int pcf1 = Convert.ToInt32(pcf);
             int fcf1 = Convert.ToInt32(fcf);
             int ecf1 = Convert.ToInt32(ecf);
             int a = 0; 
             int x = pcf1;
             int y = fcf1;
             int z = ecf1;

             if (x < y || x < z)
             {
                 Response.Write("<script> alert('Premium class fare should not be lesser than First or Economy Class Fare')");
                 a++;

             }
             if (y > x || y < z)
             {
                 Response.Write("<script> alert('First class fare should not be greater than Premuium and should be greater than Economy Class')");
                 a++;

             }
            if(z > y || z > x)
            {
                Response.Write("<script> alert('Economy  class fare should not be greater than First or Economy Class Fare')");
                a++;

            }


            if (a == 0)
            {
                IFSBO boobj = BOFactory.FSBOF.EditFS(id, depdt1, desdt1, pcf1, fcf1, ecf1);
                IFSBLL bllobj = BLLFactory.FSBLLF.Edit();
                bool success = bllobj.editfs(boobj);
            }

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            viewdata();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {

            GridView1.EditIndex = -1;
            viewdata();


        }
    }
}
-----------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TYPES
{
   public  interface IFSDAL
    {


        List<IFSBO> viewallListBO();

        bool editFSS(IFSBO bb);
    }
}

-----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TYPES
{
   public interface IFSBO
    {
        int FlightScheduleID { get; set; }
        string DepaarturePlace { get; set; }
        string DestinationPlace { get; set; }
        string Flight { get; set; }
        int AirBusID { get; set; }
        DateTime DepartureDateTime { get; set; }
        DateTime ArrivalDateTime { get; set; }

        double PremiumClassFare { get; set; }
        double FirstClassFare { get; set; }
        double EconomyClassFare { get; set; }
        int PremiumClassSeatingAvailability { get; set; }
        int FirstClassSeatingAvailability { get; set; }
        int EconomyClassSeatingAvailability { get; set; }
        double Vat { get; set; }
        double Tax { get; set; }
        int Distance { get; set; }
        bool Status { get; set; }
        string Description { get; set; }
    }
}
=======================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TYPES
{
  public  interface IFSBLL
    {
      List<IFSBO> viewallListBLL();

      bool editfs(IFSBO boobj);
    }
}
===========================================================================================
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

  <connectionStrings>
    <add name="connstr" connectionString="Data Source=intvmsql01;Intial catalog=db05tms223;User Id=pj05tms223;Password=tcstvm;" />

  </connectionStrings>

</configuration>
======================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Data.Sql;

namespace DAL
{
    class DButility
    {
        //public static SqlConnection getconnection()
        //{
        //    string con = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        //    SqlConnection conn = new SqlConnection(con);
        //    return conn;
        //}
    }
}
==================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYPES;
using BOFactory;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
   public class FSDAL:IFSDAL
    {
        List<IFSBO> fslist = new List<IFSBO>();

        public List<IFSBO> viewallListBO()
        {
            try
            {
                string ConnectionString = "Data Source = intvmsql01;" +
                   "Initial Catalog = db05tms223;"
                   + "User id=pj05tms223;"
                   + "Password=tcstvm;";

                SqlConnection connection = new SqlConnection(ConnectionString);
                //SqlConnection connection = DButility.getconnection();
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_viewfsd";
                cmd.Connection = connection;
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    int fsid = Convert.ToInt32(reader["FlightScheduleID"]);
                    string depplace = reader["DeparturePlace"].ToString();
                    string desplace = reader["DestinationPlace"].ToString();
                    string flight = reader["Flight"].ToString();
                    int abid = Convert.ToInt16(reader["AirBusID"]);
                    DateTime depdt = Convert.ToDateTime(reader["DepartureDateTime"]);
                    DateTime aridt = Convert.ToDateTime(reader["ArrivalDateTime"]);
                    double pcf = Convert.ToDouble(reader["PremiumClassFare"]);
                    double fcf = Convert.ToDouble(reader["FirstClassFare"]);
                    double ecf = Convert.ToDouble(reader["EconomyClassFare"]);
                    int pcsa = Convert.ToInt16(reader["PremiumClassSeatingAvailability"]);
                    int fcsa = Convert.ToInt16(reader["FirstClassSeatingAvailability"]);
                    int ecsa = Convert.ToInt16(reader["EconomyClassSeatingAvailability"]);
                    double vat = Convert.ToDouble(reader["Vat"]);
                    double tax = Convert.ToDouble(reader["Tax"]);
                    int dist = Convert.ToInt16(reader["Distance"]);
                    bool stat = Convert.ToBoolean(reader["Status"]);


                    IFSBO employee = BOFactory.FSBOF.viewfs(fsid, depplace, desplace, flight, abid, depdt, aridt, pcf, fcf, ecf, pcsa, fcsa, ecsa, vat, tax, dist, stat);
                    fslist.Add(employee);

                }
                connection.Close();

            }
            catch(Exception)
            {

            }
            return fslist;
        }
        public bool editFSS(IFSBO bb)
        {
            bool flag = false;
            string ConnectionString = "Data Source = intvmsql01;" + "Initial Catalog = db05tms223;" + "User id=pj05tms223;" + "Password=tcstvm;";

            SqlConnection connection = new SqlConnection(ConnectionString);
            connection.Open();
            SqlCommand command = new SqlCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "sp_editFSD";
            command.Connection = connection;
            SqlConnection conn = new SqlConnection();
            command.Parameters.AddWithValue("@FlightScheduleID", bb.FlightScheduleID);
            command.Parameters.AddWithValue("@DepartureDateTime", bb.DepartureDateTime);
            command.Parameters.AddWithValue("@ArrivalDateTime", bb.ArrivalDateTime);
            command.Parameters.AddWithValue("@PremiumClassFare", bb.PremiumClassFare);
            command.Parameters.AddWithValue("@FirstClassFare", bb.FirstClassFare);
            command.Parameters.AddWithValue("@EconomyClassFare", bb.EconomyClassFare);

            int rowaffected = command.ExecuteNonQuery();
            connection.Close();
            if (rowaffected > 0)
            {
                flag = true;
            }
            return flag;
        }
    }
}
=====================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYPES;
using DAL;

namespace DALFactory
{
  public  class FSDALF
    {



        public static List<IFSBO> viewallListBO()
        {
            IFSDAL cust = new FSDAL();
            List<IFSBO> cust1 = cust.viewallListBO();
            return cust1;
        }

        public static IFSDAL EditFS()
        {
            IFSDAL edit = new FSDAL();
            return edit;
        }
    }
}
=========================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYPES;
using BO;

namespace BOFactory
{
   public  class FSBOF
    {



        public static IFSBO viewfs(int fsid, string depplace, string desplace, string flight, int abid, DateTime depdt, DateTime aridt, double pcf, double fcf, double ecf, int pcsa, int fcsa, int ecsa, double vat, double tax, int dist, bool stat)
        {
            IFSBO n = new FSBO(fsid, depplace, desplace, flight, abid, depdt, aridt, pcf, fcf, ecf, pcsa, fcsa, ecsa, vat, tax, dist, stat);
            return n;
        }

        public static IFSBO EditFS(int id, DateTime depdt1, DateTime desdt1, int pcf1, int fcf1, int ecf1)
        {
            IFSBO b = new FSBO(id, depdt1, desdt1, pcf1, fcf1, ecf1);
            return b;
        }
    }
}
========================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYPES;
using DALFactory;

namespace BLL
{
   public class FSBLL:IFSBLL
    {
        public List<IFSBO> viewallListBLL()
        {
            List<IFSBO> obj = DALFactory.FSDALF.viewallListBO();
            return obj;
        }

        public bool editfs(IFSBO bb)
        {
            IFSDAL obj3 = DALFactory.FSDALF.EditFS();
            bool edit = obj3.editFSS(bb);
            return edit;
        }

    }
}
=====================================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYPES;
using BLL;


namespace BLLFactory
{
   public  class FSBLLF
    {
        public static IFSBLL ViewList()
        {
            IFSBLL obll = new FSBLL();
            return obll;
        }

        public static IFSBLL Edit()
        {
            IFSBLL obll1 = new FSBLL();
            return obll1;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.