使用 ASP.NET Web 应用程序的 LINQ 演示






4.53/5 (30投票s)
这是一个为希望在 ASP.NET 中开始 Linq 实现的初学者用户提供的示例应用程序。
引言
这是一个 ASP.NET Linq 演示。
背景
如果您了解如何绑定 datagrid 以及通过 ASP.NET 应用程序添加、更新和删除记录,但对 Linq 集成一无所知,那么本文将为您提供如何使用 Linq 的思路。
Using the Code
这是一个为希望在 ASP.NET 中开始 Linq 实现的初学者用户提供的示例应用程序。
步骤 1
创建一个新的 Web 应用程序项目
 
 
第二步
创建一个 Web 表单

<asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" />
    <asp:Button ID="btnAddNew" runat="server" Text="Add New" OnClick="btnAddNew_Click" />
    <table id="tblForm" runat="server">
        <tr>
            <td>Country Name:</td>
            <td><asp:TextBox ID="txtCountryName" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Country Code:</td>
            <td><asp:TextBox ID="txtCountryCode" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSave" runat="server" Text="Add" 
		OnClick="btnSave_Click" />
                <asp:Button ID="btnUpdate" runat="server" Text="Update" 
		OnClick="btnUpdate_Click" />
                <asp:Button ID="btnCancel" runat="server" Text="Cancel" 
		OnClick="btnCancel_Click" />
            </td>
        </tr>
    </table>
    <table id="tblGrid" runat="server">
        <tr>
            <td><asp:Label ID="lblID" runat="server" Visible="false"></asp:Label>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
		OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:BoundField DataField="Countryid" HeaderText="ID" />
                        <asp:BoundField DataField="CountryName" 
			HeaderText="Country Name" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkEdit" runat="server" 
				CommandArgument='<%# Eval("Countryid")%>'
                                    CommandName="cmdEdit" Text="Edlit"></asp:LinkButton>
                                  ---  
                                <asp:LinkButton ID="lnkDelete" runat="server" 
				CommandArgument='<%# Eval("Countryid")%>'
                                    CommandName="cmdDelete" Text="Delete">
			     </asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>
步骤 3
添加一个新项目 – Linq to SQL 类
 
 
步骤 4
创建一个数据库表 -- tblCountry
CREATE TABLE [dbo].[tblCountry](
	[Countryid] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[CountryCode] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[Status] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	
 CONSTRAINT [PK_tblCountry] PRIMARY KEY CLUSTERED 
(
	[Countryid] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
步骤 5
将数据库连接到项目
 
 
步骤 6
选择用于 Linq 表集成的表
 
 
步骤 7
在 web.config 文件中设置数据库连接字符串
<appSettings>
  <add key="constr" value="Data Source = machinename\SQLEXPRESS;
	Initial Catalog=test;User ID=tuser; password=tpass"/>
</appSettings>
步骤 8
编写插入记录方法
protected void btnSave_Click(object sender, EventArgs e)
        {
            using(DLCountryiesDataContext countries = new DLCountryiesDataContext())
            {
                tblCountry country = new tblCountry
                 {
                     CountryName = txtCountryName.Text.Trim(),
                     CountryCode = txtCountryCode.Text.Trim(),
                     Status = "Active"
                 };
                countries.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
                countries.tblCountries.InsertOnSubmit(country);
                countries.SubmitChanges();
                ViewData();
            }
        }
步骤 9
编写在 Gridview 中查看记录的方法
private void ViewData()
        {
            ClearForm();
            DLCountryiesDataContext db = new DLCountryiesDataContext();
            db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
            var country =
                from c in db.tblCountries
                select c;
            GridView1.DataSource = country;
            GridView1.DataBind();
        }
第 10 步
编写用于编辑和删除记录的方法
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdEdit")
            {
                ClearForm();
                DLCountryiesDataContext db = new DLCountryiesDataContext();
                db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
                var country =
                    from c in db.tblCountries
                    where (c.Countryid == Convert.ToInt32(e.CommandArgument.ToString()))
                    select c;
                lblID.Text = e.CommandArgument.ToString();
                foreach (tblCountry cntry in country)
                {
                    txtCountryName.Text = cntry.CountryName;
                    txtCountryCode.Text = cntry.CountryCode;
                }
                btnSave.Visible = false;
                btnUpdate.Visible = true;
            }
            if (e.CommandName == "cmdDelete")
            {
                DLCountryiesDataContext db = new DLCountryiesDataContext();
                db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
                var country =
                    from c in db.tblCountries
                    where (c.Countryid == Convert.ToInt32(e.CommandArgument.ToString()))
                    select c;
                db.tblCountries.DeleteAllOnSubmit(country);
                db.SubmitChanges();
                ViewData();
            }
        }
第 11 步
编写更新记录的方法
protected void btnUpdate_Click(object sender, EventArgs e)
        {
            DLCountryiesDataContext db = new DLCountryiesDataContext();
            db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
            var country = db.tblCountries.Single
		(p => p.Countryid == Convert.ToInt32(lblID.Text));
            country.CountryName = txtCountryName.Text.Trim();
            country.CountryCode = txtCountryCode.Text.Trim();
            db.SubmitChanges();
            ViewData();
        }
第 12 步
页面常用方法(不强制在页面中使用)
protected void btnView_Click(object sender, EventArgs e)
        {         
            ViewData();
            HideForm();
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            ShowForm();
            btnSave.Visible = true;
            btnUpdate.Visible = false;            
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {   
            ViewData();
            HideForm();
        }
        
        private void HideForm()
        {
            tblForm.Visible = false;
            tblGrid.Visible = true;
            btnView.Visible = false;
            btnAddNew.Visible = true;            
        }
        
        private void ShowForm()
        {
            tblForm.Visible = true;
            tblGrid.Visible = false;
            btnView.Visible = true;
            btnAddNew.Visible = false;
        }
        
        private void ClearForm()
        {
            txtCountryCode.Text = "";
            txtCountryName.Text = "";
        }
第 13 步
运行项目。
结束。
历史
- 2011 年 4 月 29 日:初始版本


