通过LINQ TO SQL类显示数据库表的数据

1.数据库操作:首先在数据库创建一张简单的表SPJ

2.新建一个ASP.NET空网站

3.新建一个Web窗体,命名为ShowData.aspx

  在源码界面添加两个控件:Button控件和Gridview控件

 <div>
            <asp:Button ID="BtnShow" runat="server" Text="单击显示Gridview表" OnClick="BtnShow_Click" />
            <asp:GridView ID="GridView" runat="server">
            </asp:GridView>
        </div>

可以看到设计界面

4.新建一个linq to sql类,命名为:DataClasses.dbml,在服务器资源管理器中进行数据库连接,连接到1中的数据库,将表SPJ拖到设计界面中

5.新建一个类,命名为:DALShowData.cs

代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// DALShowdata 的摘要说明
/// </summary>

namespace DAL
{
    public class DALShowdata
    {

        public IEnumerable DALdataQuary()
        {
            DataClassesDataContext db=new DataClassesDataContext();
            IEnumerable a = from b in db.SPJ
                select new
                {
                    b.SNO,
                    b.PNO,
                    b.JNO,
                    b.QTY
                };
            return a;

        }
    }


}

6.打开后台代码Showdata.aspx.cs,编写Button单击事件代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
public partial class ShowData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnShow_Click(object sender, EventArgs e)
    {
        DALShowdata dalShowdata=new DALShowdata();
        var data = dalShowdata.DALdataQuary();
        this.GridView.DataSource = data;
        this.GridView.DataBind();
    }
}

7.在浏览器中查看Showdata.aspx,查看结果

单击按钮可以看到SPJ表的数据:

原文地址:https://www.cnblogs.com/wiming/p/3470300.html