C# 如何在asp.net中显示HTML表格中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19602917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:24:03  来源:igfitidea点击:

how to display data in HTML table in asp.net

c#asp.net

提问by Velu

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.

我正在编写一个 ASP.NET 页面,该页面从数据库中读取数据并需要将其显示在 HTML 表中。我不想使用 gridView。

Here is the code I tried using c#:

这是我尝试使用 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:

这是我的 html 代码:

<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>

回答by Monika

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())%>

<%=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

还可以选择使用转发器控件并将数据库中的数据绑定到项目模板

回答by Rajaram Shelar

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.

如果你想通过 ajax 调用,你可以参考你合适的 jquery 版本。在后面的代码中编写 webmethod。从 Ajax 调用它并将列表详细信息绑定到表。波纹管是代码。

Web Methodin default.aspx.cs

default.aspx.cs 中的Web 方法

 [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 callin aspx

aspx中的Jquery AJAX调用

<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.

希望这对你有帮助。

回答by Sikha Rath

      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>

回答by gt2

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;
        }
    }
}