前台:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MySQL_Demo.WebForm1" %>




<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title></title>

    <style type="text/css">

        table {

        border:2px double red;

        }

        th {

            border:2px double yellow;

            width:100px;

            color:blue;

        }

        td {

        border:1px double yellow;

            width:100px;

            color:blue;

        

        }



    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <%System.Data.DataTable tb = (System.Data.DataTable)Session["gtb"];%>

            <table style="width: 100%;">

                <tr>

                    <th>编号</th>

                    <th>城市</th>

                    <th>城市代码</th>

                    <th>描述</th>

                    <th>人口</th>

                </tr>

                <%foreach (System.Data.DataRow item in tb.Rows)

                  {%>

                <tr>

                    <td><%:item[0] %></td>

                    <td><%:item[1] %></td>

                    <td><%:item[2] %></td>

                    <td><%:item[3] %></td>

                    <td><%:item[4] %></td>

                </tr>

                <%} %>

            </table>

        </div>

    </form>

</body>

</html>

后台:

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

//引入MySQL的驱动

using MySql;

using MySql.Data;

using MySql.Data.MySqlClient;


namespace MySQL_Demo

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            string strcon = ConfigurationManager.AppSettings["mysqlcon"].ToString();

            string sql = "select * from city";

            using (MySqlConnection con = new MySqlConnection(strcon))

            {

                MySqlCommand cmd = new MySqlCommand();

                cmd.CommandText = sql;

                cmd.Connection = con;

                MySqlDataAdapter dr = new MySqlDataAdapter(cmd);

                DataTable tb = new DataTable();

                dr.Fill(tb);

                Session["gtb"] = tb;//设置session,传值到前台


            }

        }

    }

}

效果显示:wKiom1RVn97hFXlPAAmds3-9Sak144.jpg