Complete a three-tier architecture case-2 from scratch (step 01)

Step 01


2. Operation steps

Before starting, make sure that Visual Studio and SQL Server Management Studio have been successfully installed, and the SQL service has been opened.

2.1 Build database and table

Copy the name from the image below. It will be used in later steps. (DESKTOP-ADKCE™)

image.png

image.png

Y_strong
image.png

image.png

Create a table structure according to the topic requirements. (Note that the data type of the gender field is not set to Char(4) as required by the title, but is set to Char(2), because a Chinese occupies 2 digits)image.png

Then set Oid as primary key and set it to auto increment.
image.png
(Note that Char(4) in the figure below should be Char(2) before it has been modified. Don’t be confused by the figure below. I gave the wrong picture...)
image.png

2.2 Add test data

After setting the structure of the table, click the refresh button in the figure below, and then choose to edit the first 200 rows.
image.png

image.png

Add a few pieces of test data at will.
Let’s unify the rules first, that is, the name can only have 2-4 Chinese characters, the gender can only be male or female, the phone number is 11 digits, and the last three fields are all 1-3 digits. When layer B makes logical judgments, it mainly verifies the described rules. 
image.png

2.3 Create a project in VS

Select ASP.NET Web Application (YYYDemo P_ULayer)
image.png

click OKimage.png

This is what it looks like now
image.png

Right click on the solution - Add - New Project.image.png

Select the class library project. (P_BLayer)image.png

In the same steps, create a new class library project. (P_DLayer)
The solution now is the situation shown in the picture below.
image.png

2.4 Adding references

Add a reference to the P_BLayer project in the P_ULayer project, and a reference to the P_DLayer project in the P_BLayer project.

Add a reference to B in U:
image.png
image.png

Add a reference to D in B:
image.png

image.png

Now it looks like this:
image.png

Modify the assembly name and default namespace name 
image.png

image.png

In the same way, modify the two properties of the B-layer and D-layer projects, both of which are modified to YYYDemo.XXX
image.png

image.png

2.5 Adding classes and pages

①: Add class in B:
image.png

BLayer
image.png

②: In the same way, add a class (DLayer) in D
③: In the U layer project, add a .aspx web form and a .master master page
③-1: Add a web form
image.png

ShowAll
image.png

③-2: Add the master page
image.png


Site
image.png




to complete the above operations, the current structure should be like this:
image.png

2.6 Establish a connection between VS and SSMS

image.png

image.png

image.png

Now take the name from the step "2.1 Building a database and building a table"
image.png

You can see that the connection has been established.
image.png

image.png

Copy the connection string in the figure below 
Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True
image.png

2.7 Realize the display function

①: Modify the code of D_Layer.cs, and take the connection string in "2.6 Steps".
The red box is the newly added or modified code, and it has the same meaning in the subsequent steps.
image.png

image.png

code show as below:

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

using System.Data;
using System.Data.SqlClient;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }

        //关闭连接
        public void D_CloseConn()
        {
    
    
            CreateConnection().Close();
        }

        //获取全部的账户信息,以DataSet数据类型返回
        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
    }
}

②: Modify the code of B_Layer
image.png

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

using YYYDemo.P_DLayer;
using System.Data;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗


namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);

        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            return new DLayer().GetAllAccount_TO_DataSet();
        }

        public void B_CloseConn()
        {
    
    
            new DLayer().D_CloseConn();
        }
    }
}

③-1: Modify the ShowAll page of the U layer
image.png

Then go to the design interface to modify the GridView.
image.png

This data field is very critical and corresponds to the fields in the data table one by one, so it needs to be the same as the name of the field in the data table.
The header text is the text displayed on the interface.
image.png

In the same way, add the following columns:
image.png

The corresponding GridView code is as follows: image.png
(The SortExpression property can be deleted, because we don't use it to implement any functions.)

Code for ShowAll.aspx as of now

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            
            <div id="Div_lbl_Topic">
                <asp:Label runat="server" ID="lbl_Topic" Text="小 区 业 主 列 表"></asp:Label>
            </div>
            
            <asp:GridView ID="gView" runat="server"
                AllowPaging="True"
                AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="姓名" SortExpression="Name" />
                    <asp:BoundField DataField="Sex" HeaderText="性别" />
                    <asp:BoundField DataField="Phone" HeaderText="联系电话" SortExpression="Phone" />
                    <asp:BoundField DataField="BuildNum" HeaderText="楼号" SortExpression="BuildNum" />
                    <asp:BoundField DataField="Unit" HeaderText="单元" SortExpression="Unit" />
                    <asp:BoundField DataField="RoomNum" HeaderText="房间号" SortExpression="RoomNum" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Write the code for ShowAll.aspx.cs
image.png

image.png

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

using YYYDemo.P_BLayer;

namespace P_ULayer
{
    
    
    public partial class ShowAll : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            this.gView.DataSource = new BLayer().GetAllAccount_TO_DataSet();
            this.gView.DataBind();
            new BLayer().B_CloseConn();
        }
    }
}

Run the test: ( Must make the current active window of VS be ShowAll.aspx or ****ShowAll.aspx.cs to press F5 to run )
image.png
You can see that the information of the data table can be displayed normally.

2.8 Create a new content page, and edit the UI of the master page, content page and ShowAll page


image.png
①: To write the table content hidden by Site.Master, you can directly view the following code.

image.png

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="P_ULayer.Site" %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div id="Div_hLink_TO_01">
                <asp:HyperLink ID="hLink_TO_ShowAll" runat="server" NavigateUrl="~/ShowAll.aspx" Target="_self" Text="返回主页"></asp:HyperLink>
            </div>
            

            <asp:ContentPlaceHolder ID="ContentPlaceHolder_DivLabel" runat="server">
            </asp:ContentPlaceHolder>

            <br />
            <br />

            <table id="tableUI">
                <tr>
                    <td style="width: 48%" class="td_Left">
                        <asp:Label ID="lbl_Name" runat="server" Text="姓名:"></asp:Label>
                    </td>
                    <td style="width: 50%">
                        <asp:TextBox ID="textBox_Name" runat="server" Font-Size="16pt"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="td_Left">
                        <asp:Label ID="lbl_Sex" runat="server" Text="性别:"></asp:Label>
                    </td>
                    <td>
                        <asp:RadioButton ID="radioBtn_Boy" runat="server" GroupName="Sex" Text="男" Checked="True" />
                        <asp:RadioButton ID="radioBtn_Girl" runat="server" GroupName="Sex" Text="女" />
                    </td>
                </tr>
                <tr>
                    <td class="td_Left">
                        <asp:Label ID="lbl_Phone" runat="server" Text="联系电话:"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="textBox_Phone" runat="server" Font-Size="16pt"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="td_Left">
                        <asp:Label ID="lbl_BuildNum" runat="server" Text="楼号:"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="textBox_BuildNum" runat="server" Font-Size="16pt"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="td_Left">
                        <asp:Label ID="lbl_Unit" runat="server" Text="单元:"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="textBox_Unit" runat="server" Font-Size="16pt"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="td_Left">
                        <asp:Label ID="lbl_RoomNum" runat="server" Text="房间号:"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="textBox_RoomNum" runat="server" Font-Size="16pt"></asp:TextBox>
                    </td>
                </tr>
            </table>

            <br />
            <br />
            
            <asp:ContentPlaceHolder ID="ContentPlaceHolder_DivButton" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>

②: Add content page:
image.png
You can see the newly created content page as shown in the figure below:
image.png

In the same way, create a new content page, and then modify the names of the two content pages, the specific effect is as follows:
image.png

③: Edit the code of the content page
③-1: The edited AddAccount content page:image.png

In the design interface, double-click the Button to add a click event to it.
image.png
The function in the figure below is automatically created after double-clickingimage.png

Go back to the .aspx of the AddAccount content page, and you can see that
image.png
there is an additional attribute automatically.

As of now, the code for the AddAccount.aspx content page is as follows:

<%@ Page Title="新增业主" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AddAccount.aspx.cs" Inherits="YYYDemo.P_ULayer.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder_DivLabel" runat="server">
    <div id="Div_lbl_Topic">
        <asp:Label ID="lbl_Topic" runat="server" Text="新 增 业 主"></asp:Label>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder_DivButton" runat="server">
    <div id="Div_btnSubmit">
        <asp:Button ID="btnSubmit" runat="server" class="CSS_class_btnSubmit" Text="提交" OnClick="btnSubmit_Click"/>
    </div>
</asp:Content>

③-2: Follow the same steps as ③-1 to modify the code of the AlterAccount content page.
image.png

image.png

image.png

Code for AlterAccount.aspx as of now:

<%@ Page Title="修改业主" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AlterAccount.aspx.cs" Inherits="YYYDemo.P_ULayer.WebForm2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder_DivLabel" runat="server">
    <div id="Div_lbl_Topic">
        <asp:Label ID="lbl_Topic" runat="server" Text="修 改 业 主"></asp:Label>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder_DivButton" runat="server">
    <div id="Div_btnSubmit">
        <asp:Button ID="btnSubmit" runat="server" Text="提交" class="CSS_class_btnSubmit" OnClick="btnSubmit_Click" />
    </div>
</asp:Content>

④: Add a link control to the ShowAll page
image.png

image.png

The code for the ShowAll page as of now:

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            
            <div id="Div_lbl_Topic">
                <asp:Label runat="server" ID="lbl_Topic" Text="小 区 业 主 列 表"></asp:Label>
            </div>
            
            <div>
                <br /><br />
                <asp:HyperLink Target="_self" NavigateUrl="~/AddAccount.aspx" runat="server" ID="hLink_AddAccount" Text="新增业主"></asp:HyperLink>
                <br /><br /><br /><br />
            </div>

            <asp:GridView ID="gView" runat="server"
                AllowPaging="True"
                AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="姓名" SortExpression="Name" />
                    <asp:BoundField DataField="Sex" HeaderText="性别" />
                    <asp:BoundField DataField="Phone" HeaderText="联系电话" SortExpression="Phone" />
                    <asp:BoundField DataField="BuildNum" HeaderText="楼号" SortExpression="BuildNum" />
                    <asp:BoundField DataField="Unit" HeaderText="单元" SortExpression="Unit" />
                    <asp:BoundField DataField="RoomNum" HeaderText="房间号" SortExpression="RoomNum" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Run the test:
image.png
image.png

You can normally enter the new owner interface and return to the home page.

2.9 Realize the function of adding new owners

First modify the code of DLayer
image.png

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

using System.Data;
using System.Data.SqlClient;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }

        //关闭连接
        public void D_CloseConn()
        {
    
    
            CreateConnection().Close();
        }

        //获取全部的账户信息,以DataSet数据类型返回
        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
        
        //添加一个账户
        public void AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                "INSERT INTO owner(name,sex,phone,buildnum,unit,roomnum) " +
                "VALUES(N'{0}','{1}',N'{2}',N'{3}',N'{4}',N'{5}')"
                , name, sex, phone, buildNum, unit, roomNum),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
    }
}

Then modify the code of BLayer
image.png

image.png

image.png

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

using YYYDemo.P_DLayer;
using System.Data;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗


namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);

        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            return new DLayer().GetAllAccount_TO_DataSet();
        }

        public void B_CloseConn()
        {
    
    
            new DLayer().D_CloseConn();
        }


        string errorStr = "";//这个也可以设置成局部变量,只不过让RegularCheck_Add(Update)_TO_Bool函数多传递一个参数而已。
        //添加账户时正则表达式对输入数据的验证
        private bool RegularCheck_Add_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";//2-4个中文
            string rStr_Phone = @"^\d{11}$";//11位数字
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";//1-3位数字

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            DataTable table = GetAllAccount_TO_DataSet().Tables[0];

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < table.Rows.Count; i++)
            {
    
    

                if (phone == table.Rows[i][3].ToString())
                    equal_Phone = true;

                if (
                    buildNum == table.Rows[i][4].ToString() &&
                    unit == table.Rows[i][5].ToString() &&
                    roomNum == table.Rows[i][6].ToString()
                    )
                    equal_Position = true;
            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }

            B_CloseConn();
            return flag;
        }

        //添加一个账户
        public string AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            if (RegularCheck_Add_TO_Bool(name, sex, phone, buildNum, unit, roomNum))
            {
    
    
                errorStr = "新增业主信息成功!";
                new DLayer().AddAnAccount(name, sex, phone, buildNum, unit, roomNum);
            }
            else
                errorStr += "\n新增业主信息失败!";
            return errorStr;
        }
    }
}

Modify AddAccount.aspx.cs file
image.png

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

using YYYDemo.P_BLayer;

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

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
    
    
            char sex = '男';
            if ((Master.FindControl("radioBtn_Girl") as RadioButton).Checked)
                sex = '女';


            string message = new BLayer().AddAnAccount(
                        (Master.FindControl("textBox_Name") as TextBox).Text.ToString(),
                        sex,
                        (Master.FindControl("textBox_Phone") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_BuildNum") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_Unit") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_RoomNum") as TextBox).Text.ToString()
                        );
            BLayer.MessageBox(IntPtr.Zero, message, "提示!", 0);
        }
    }
}

  1. Master.FindControl("IDName") 
    This code means to find the control on the master page by id
  2. BLayer.MessageBox(IntPtr.Zero, message, “Prompt!”, 0); 
    The second parameter (string type) indicates the text displayed in the prompt box, and the third parameter (string type) is the text in the upper left corner of the prompt box , the fourth parameter (int type) is the number of buttons, 0 is an OK button, 1 is an OK button, and a cancel button (used later in the delete function).

Run the test:
when the correct data is entered:
image.png

When entering incorrect data:image.png

You can see that the verification and addition can be performed normally. After the addition is successful, go to the SQL server to look at the data in the table and find that it has been added.
image.png

2.10 Realize the function of modifying owner information

First modify the code of DLayer
image.png

image.png

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

using System.Data;
using System.Data.SqlClient;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }

        //关闭连接
        public void D_CloseConn()
        {
    
    
            CreateConnection().Close();
        }

        //获取全部的账户信息,以DataSet数据类型返回
        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
        
        //添加一个账户
        public void AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                "INSERT INTO owner(name,sex,phone,buildnum,unit,roomnum) " +
                "VALUES(N'{0}','{1}',N'{2}',N'{3}',N'{4}',N'{5}')"
                , name, sex, phone, buildNum, unit, roomNum),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }

        //通过手机号获得一个账户的信息,以DataSet数据类型返回;
        //这个函数是为了在B层通过手机号获取账户的id
        public DataSet GetAnAccountByPhone_TO_DataSet(string phone)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE phone=N'{0}'", phone),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }

        //通过id获得一个账户的信息,以DataSet数据类型返回
        public DataSet GetAnAccountByIndex_TO_DataSet(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE Oid={0}", index),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }


        //修改一行信息
        public void UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                    "UPDATE owner SET name=N'{0}',sex='{1}',phone=N'{2}',buildnum=N'{3}',unit=N'{4}',roomnum=N'{5}' " +
                    "WHERE Oid={6}; ", name, sex, phone, buildNum, unit, roomNum, index),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
    }
}

Modify the code of BLayer
image.png

image.png

image.png

image.png

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

using YYYDemo.P_DLayer;
using System.Data;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗


namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);

        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            return new DLayer().GetAllAccount_TO_DataSet();
        }

        public void B_CloseConn()
        {
    
    
            new DLayer().D_CloseConn();
        }


        string errorStr = "";//这个也可以设置成局部变量,只不过让RegularCheck_Add(Update)_TO_Bool函数多传递一个参数而已。
        //添加账户时正则表达式对输入数据的验证
        private bool RegularCheck_Add_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";//2-4个中文
            string rStr_Phone = @"^\d{11}$";//11位数字
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";//1-3位数字

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            DataTable table = GetAllAccount_TO_DataSet().Tables[0];

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < table.Rows.Count; i++)
            {
    
    

                if (phone == table.Rows[i][3].ToString())
                    equal_Phone = true;

                if (
                    buildNum == table.Rows[i][4].ToString() &&
                    unit == table.Rows[i][5].ToString() &&
                    roomNum == table.Rows[i][6].ToString()
                    )
                    equal_Position = true;
            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }

            B_CloseConn();
            return flag;
        }

        //添加一个账户
        public string AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            if (RegularCheck_Add_TO_Bool(name, sex, phone, buildNum, unit, roomNum))
            {
    
    
                errorStr = "新增业主信息成功!";
                new DLayer().AddAnAccount(name, sex, phone, buildNum, unit, roomNum);
            }
            else
                errorStr += "\n新增业主信息失败!";
            return errorStr;
        }
        
        
        //通过手机号获取该行数据的索引,为下面的GetAnAccountByIndex_TO_DataSet()函数提供作用
        public int GetIndexByPhone_TO_Int(string phone)
        {
    
    
            return Convert.ToInt32(
                new DLayer().GetAnAccountByPhone_TO_DataSet(phone).Tables[0].Rows[0][0].ToString());
        }

        //通过索引获取该行数据的全部信息,以DataSet数据类型返回
        public DataSet GetAnAccountByIndex_TO_DataSet(int index)
        {
    
    
            return new DLayer().GetAnAccountByIndex_TO_DataSet(index);
        }

        //修改一个账户的信息
        public string UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            if (RegularCheck_Update_TO_Bool(name, sex, phone, buildNum, unit, roomNum, index))
            {
    
    
                errorStr = "修改业主信息成功!";
                new DLayer().UpdateAnAccount(name, sex, phone, buildNum, unit, roomNum, index);
            }
            else
                errorStr += "\n修改业主信息失败!";
            return errorStr;
        }



        //修改账户时正则表达式对输入数据的验证
        //修改个人信息,需要验证 手机号 和 住房位置 是否 *跟别人* 重复;还需验证数据是否合理
        private bool RegularCheck_Update_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";
            string rStr_Phone = @"^\d{11}$";
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            DataTable table = GetAllAccount_TO_DataSet().Tables[0];

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < table.Rows.Count; i++)
            {
    
    
                if (Convert.ToInt32(table.Rows[i][0].ToString())
                    != index)
                {
    
    
                    if (phone == table.Rows[i][3].ToString())
                        equal_Phone = true;

                    if (
                        buildNum == table.Rows[i][4].ToString() &&
                        unit == table.Rows[i][5].ToString() &&
                        roomNum == table.Rows[i][6].ToString()
                        )
                        equal_Position = true;
                }

            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }

            B_CloseConn();
            return flag;
        }

    }
}

Modify the events of the GridView control on the ShowAll page, double-click the two events in the figure below, and let it automatically add two methods.
image.png

image.png

image.png

Add two ButtonField columns to the GridView.
image.png

image.png

You can see that this column has come out.
Proceed to edit the columns.
image.png

Change the CommandName to modify this column to Y_Update
image.png

You can see the code shown in the following figure on the source code of the ShowALl.aspx page:
image.png

As of now, the code for ShowAll.aspx:

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            
            <div id="Div_lbl_Topic">
                <asp:Label runat="server" ID="lbl_Topic" Text="小 区 业 主 列 表"></asp:Label>
            </div>
            
            <div>
                <br /><br />
                <asp:HyperLink Target="_self" NavigateUrl="~/AddAccount.aspx" runat="server" ID="hLink_AddAccount" Text="新增业主"></asp:HyperLink>
                <br /><br /><br /><br />
            </div>

            <asp:GridView ID="gView" runat="server"
                AllowPaging="True"
                AutoGenerateColumns="False" OnPageIndexChanging="gView_PageIndexChanging" OnRowCommand="gView_RowCommand">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="姓名" SortExpression="Name" />
                    <asp:BoundField DataField="Sex" HeaderText="性别" />
                    <asp:BoundField DataField="Phone" HeaderText="联系电话" SortExpression="Phone" />
                    <asp:BoundField DataField="BuildNum" HeaderText="楼号" SortExpression="BuildNum" />
                    <asp:BoundField DataField="Unit" HeaderText="单元" SortExpression="Unit" />
                    <asp:BoundField DataField="RoomNum" HeaderText="房间号" SortExpression="RoomNum" />
                    <asp:ButtonField CommandName="Y_Update" HeaderText="操作" ShowHeader="True" Text="修改" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Continue to modify the code of ShowAll.aspx.cs, and implement the function of changing pages and jumping to the AlterAccount page on the ShowAll page.
image.png

As of now, the code for ShowAll.aspx.cs:

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

using YYYDemo.P_BLayer;

namespace P_ULayer
{
    
    
    public partial class ShowAll : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            this.gView.DataSource = new BLayer().GetAllAccount_TO_DataSet();
            this.gView.DataBind();
            new BLayer().B_CloseConn();
        }

        protected void gView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
    
    
            if (e.CommandName == "Y_Update" || e.CommandName == "Y_Delete")
            {
    
    
                //获取 操作列 或者 删除列 点击的是GridView的哪一行
                int gViewSelect_Index = Convert.ToInt32(e.CommandArgument);
                //将点击的这一行的手机号(因为手机号不可重复)的业主的Oid字段的值传给 全局变量 Application["Index"] 
                Application["Index"] = new BLayer().GetIndexByPhone_TO_Int(
                    this.gView.Rows[gViewSelect_Index].Cells[2].Text.ToString()
                    );

                //这个代码块也就是实现了 : 点击的哪一行 ---> 手机号 ---> Oid ---> Application["Index"]
            }

            if (e.CommandName == "Y_Update")
                Response.Redirect("AlterAccount.aspx");

            if (e.CommandName == "Y_Delete")
            {
    
    
                //TODO
            }

            new BLayer().B_CloseConn();
        }

        protected void gView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
    
    
            this.gView.PageIndex = e.NewPageIndex;
            gView.DataBind();
        }
    }
}

Modify the code of AlterAccount.cs:
image.png

image.png

Run the test:
image.png

image.png

no problem

2.11 Realize the function of deleting owner information

DLayer
image.png

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

using System.Data;
using System.Data.SqlClient;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }

        //关闭连接
        public void D_CloseConn()
        {
    
    
            CreateConnection().Close();
        }

        //获取全部的账户信息,以DataSet数据类型返回
        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
        
        //添加一个账户
        public void AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                "INSERT INTO owner(name,sex,phone,buildnum,unit,roomnum) " +
                "VALUES(N'{0}','{1}',N'{2}',N'{3}',N'{4}',N'{5}')"
                , name, sex, phone, buildNum, unit, roomNum),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }

        //通过手机号获得一个账户的信息,以DataSet数据类型返回;
        //这个函数是为了在B层通过手机号获取账户的id
        public DataSet GetAnAccountByPhone_TO_DataSet(string phone)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE phone=N'{0}'", phone),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }

        //通过id获得一个账户的信息,以DataSet数据类型返回
        public DataSet GetAnAccountByIndex_TO_DataSet(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE Oid={0}", index),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }


        //修改一行信息
        public void UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                    "UPDATE owner SET name=N'{0}',sex='{1}',phone=N'{2}',buildnum=N'{3}',unit=N'{4}',roomnum=N'{5}' " +
                    "WHERE Oid={6}; ", name, sex, phone, buildNum, unit, roomNum, index),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }

        //删除一行信息
        public void DeleteAnAccount(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format("DELETE FROM owner WHERE Oid = {0}", index),
                conn);
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
    }
}

BLayer
image.png

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

using YYYDemo.P_DLayer;
using System.Data;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗


namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);

        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            return new DLayer().GetAllAccount_TO_DataSet();
        }

        public void B_CloseConn()
        {
    
    
            new DLayer().D_CloseConn();
        }


        string errorStr = "";//这个也可以设置成局部变量,只不过让RegularCheck_Add(Update)_TO_Bool函数多传递一个参数而已。
        //添加账户时正则表达式对输入数据的验证
        private bool RegularCheck_Add_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";//2-4个中文
            string rStr_Phone = @"^\d{11}$";//11位数字
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";//1-3位数字

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            DataTable table = GetAllAccount_TO_DataSet().Tables[0];

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < table.Rows.Count; i++)
            {
    
    

                if (phone == table.Rows[i][3].ToString())
                    equal_Phone = true;

                if (
                    buildNum == table.Rows[i][4].ToString() &&
                    unit == table.Rows[i][5].ToString() &&
                    roomNum == table.Rows[i][6].ToString()
                    )
                    equal_Position = true;
            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }

            B_CloseConn();
            return flag;
        }

        //添加一个账户
        public string AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            if (RegularCheck_Add_TO_Bool(name, sex, phone, buildNum, unit, roomNum))
            {
    
    
                errorStr = "新增业主信息成功!";
                new DLayer().AddAnAccount(name, sex, phone, buildNum, unit, roomNum);
            }
            else
                errorStr += "\n新增业主信息失败!";
            return errorStr;
        }
        
        
        //通过手机号获取该行数据的索引,为下面的GetAnAccountByIndex_TO_DataSet()函数提供作用
        public int GetIndexByPhone_TO_Int(string phone)
        {
    
    
            return Convert.ToInt32(
                new DLayer().GetAnAccountByPhone_TO_DataSet(phone).Tables[0].Rows[0][0].ToString());
        }

        //通过索引获取该行数据的全部信息,以DataSet数据类型返回
        public DataSet GetAnAccountByIndex_TO_DataSet(int index)
        {
    
    
            return new DLayer().GetAnAccountByIndex_TO_DataSet(index);
        }

        //修改一个账户的信息
        public string UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            if (RegularCheck_Update_TO_Bool(name, sex, phone, buildNum, unit, roomNum, index))
            {
    
    
                errorStr = "修改业主信息成功!";
                new DLayer().UpdateAnAccount(name, sex, phone, buildNum, unit, roomNum, index);
            }
            else
                errorStr += "\n修改业主信息失败!";
            return errorStr;
        }



        //修改账户时正则表达式对输入数据的验证
        //修改个人信息,需要验证 手机号 和 住房位置 是否 *跟别人* 重复;还需验证数据是否合理
        private bool RegularCheck_Update_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";
            string rStr_Phone = @"^\d{11}$";
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            DataTable table = GetAllAccount_TO_DataSet().Tables[0];

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < table.Rows.Count; i++)
            {
    
    
                if (Convert.ToInt32(table.Rows[i][0].ToString())
                    != index)
                {
    
    
                    if (phone == table.Rows[i][3].ToString())
                        equal_Phone = true;

                    if (
                        buildNum == table.Rows[i][4].ToString() &&
                        unit == table.Rows[i][5].ToString() &&
                        roomNum == table.Rows[i][6].ToString()
                        )
                        equal_Position = true;
                }

            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }

            B_CloseConn();
            return flag;
        }

        //删除一个账户
        public string DeleteAnAccount(int index)
        {
    
    
            errorStr = "删除业主信息成功!";
            new DLayer().DeleteAnAccount(index);
            return errorStr;
        }

    }
}

ShowAll.aspx
image.png

image.png

image.png

image.png

image.png

image.png

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            
            <div id="Div_lbl_Topic">
                <asp:Label runat="server" ID="lbl_Topic" Text="小 区 业 主 列 表"></asp:Label>
            </div>
            
            <div>
                <br /><br />
                <asp:HyperLink Target="_self" NavigateUrl="~/AddAccount.aspx" runat="server" ID="hLink_AddAccount" Text="新增业主"></asp:HyperLink>
                <br /><br /><br /><br />
            </div>

            <asp:GridView ID="gView" runat="server"
                AllowPaging="True"
                AutoGenerateColumns="False" OnPageIndexChanging="gView_PageIndexChanging" OnRowCommand="gView_RowCommand">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="姓名" SortExpression="Name" />
                    <asp:BoundField DataField="Sex" HeaderText="性别" />
                    <asp:BoundField DataField="Phone" HeaderText="联系电话" SortExpression="Phone" />
                    <asp:BoundField DataField="BuildNum" HeaderText="楼号" SortExpression="BuildNum" />
                    <asp:BoundField DataField="Unit" HeaderText="单元" SortExpression="Unit" />
                    <asp:BoundField DataField="RoomNum" HeaderText="房间号" SortExpression="RoomNum" />
                    <asp:ButtonField CommandName="Y_Update" HeaderText="操作" ShowHeader="True" Text="修改" />
                    <asp:ButtonField CommandName="Y_Delete" HeaderText="操作" ShowHeader="True" Text="删除" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Modify the code of ShowAll.aspx.cs
image.png

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

using YYYDemo.P_BLayer;

namespace P_ULayer
{
    
    
    public partial class ShowAll : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            this.gView.DataSource = new BLayer().GetAllAccount_TO_DataSet();
            this.gView.DataBind();
            new BLayer().B_CloseConn();
        }

        protected void gView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
    
    
            if (e.CommandName == "Y_Update" || e.CommandName == "Y_Delete")
            {
    
    
                //获取 操作列 或者 删除列 点击的是GridView的哪一行
                int gViewSelect_Index = Convert.ToInt32(e.CommandArgument);
                //将点击的这一行的手机号(因为手机号不可重复)的业主的Oid字段的值传给 全局变量 Application["Index"] 
                Application["Index"] = new BLayer().GetIndexByPhone_TO_Int(
                    this.gView.Rows[gViewSelect_Index].Cells[2].Text.ToString()
                    );

                //这个代码块也就是实现了 : 点击的哪一行 ---> 手机号 ---> Oid ---> Application["Index"]
            }

            if (e.CommandName == "Y_Update")
                Response.Redirect("AlterAccount.aspx");

            if (e.CommandName == "Y_Delete")
            {
    
    
                if (BtnDelete() == 1)
                {
    
    
                    new BLayer().DeleteAnAccount(Convert.ToInt32(Application["Index"]));
                    Response.Redirect("ShowAll.aspx");
                }
            }

            new BLayer().B_CloseConn();
        }

        protected void gView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
    
    
            this.gView.PageIndex = e.NewPageIndex;
            gView.DataBind();
        }
        private int BtnDelete()
        {
    
    
            return BLayer.MessageBox(IntPtr.Zero, "确定要删除这条数据吗?", "警告!", 1);
        }
    }
}

Run the test:
I just added a lot of data here:
image.png

As you can see, the page change function is normal:
image.png

image.png

The deletion operation is performed as follows:
image.png

image.png

normal


dividing line one

Up to now, the addition, deletion, modification and query on the SQL server database have been completed. I haven’t added much to the style sheet. It seems that I just added a style with a font size of 16pt to the TextBox of the modified and deleted page.
In the next part I will add style sheets and styles, and complete the operation of connecting to MySQL.
Entity classes and support for different databases may be added, themes and skins are also planned. Maybe add an avatar too.

The current time after the completion of the above content: May 22, 2019 00:32:39


2.12 Add entity classes to pass data instead of DataSet

Create a new Entity class library project
image.png

image.png

Modify the assembly name and default namespace name of the Entity project
image.png

and add an Owner class
image.png

Edit the code of Owner.cs
image.png

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

namespace YYYDemo.Entity
{
    
    
    public class Owner
    {
    
    
        private int oid;
        private string name;
        private char sex;
        private string phone;
        private string buildNum;
        private string unit;
        private string roomNum;
        public int Oid
        {
    
    
            set {
    
     oid = value; }
            get {
    
     return oid; }
        }
        public string Name
        {
    
    
            set {
    
     name = value; }
            get {
    
     return name; }
        }
        public char Sex
        {
    
    
            set {
    
     sex = value; }
            get {
    
     return sex; }
        }
        public string Phone
        {
    
    
            set {
    
     phone = value; }
            get {
    
     return phone; }
        }
        public string BuildNum
        {
    
    
            set {
    
     buildNum = value; }
            get {
    
     return buildNum; }
        }
        public string Unit
        {
    
    
            set {
    
     unit = value; }
            get {
    
     return unit; }
        }
        public string RoomNum
        {
    
    
            set {
    
     roomNum = value; }
            get {
    
     return roomNum; }
        }
    }
}

Add a reference. After adding, it should be as shown in the figure below:
image.png


 
Modify the DLayer class of the P_DLayer project of the D layer
image.png

Modify the BLayer class of the P_BLayer project of the B layer
image.png

Modify the ShowAll.aspx.cs of the P_ULayer project of the U layer
image.png

Modify the code of AlterAccount.aspx.cs of the P_ULayer project of the U layer
image.png

Run the test, found no problem.


2.13 Current Code

1. When redundant codes are not deleted:

DLayer.cs

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

using System.Data;
using System.Data.SqlClient;
using YYYDemo.Entity;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }

        //关闭连接
        public void D_CloseConn()
        {
    
    
            CreateConnection().Close();
        }

        //获取全部的账户信息,以DataSet数据类型返回
        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
        public IList<Owner> GetAllAccount()
        {
    
    
            List<Owner> owners = new List<Owner>();

            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
            {
    
    
                Owner owner = new Owner();
                owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[i][0].ToString());
                owner.Name = dSet.Tables[0].Rows[i][1].ToString();
                owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[i][2].ToString());
                owner.Phone = dSet.Tables[0].Rows[i][3].ToString();
                owner.BuildNum = dSet.Tables[0].Rows[i][4].ToString();
                owner.Unit = dSet.Tables[0].Rows[i][5].ToString();
                owner.RoomNum = dSet.Tables[0].Rows[i][6].ToString();
                owners.Add(owner);
            }
            conn.Close();
            return owners;
        }

        //添加一个账户
        public void AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                "INSERT INTO owner(name,sex,phone,buildnum,unit,roomnum) " +
                "VALUES(N'{0}','{1}',N'{2}',N'{3}',N'{4}',N'{5}')"
                , name, sex, phone, buildNum, unit, roomNum),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
        

        //通过手机号获得一个账户的信息,以DataSet数据类型返回;
        //这个函数是为了在B层通过手机号获取账户的id
        public DataSet GetAnAccountByPhone_TO_DataSet(string phone)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE phone=N'{0}'", phone),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
        public Owner GetAnAccountByPhone_TO_Owner(string phone)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE phone=N'{0}'", phone),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");

            Owner owner = new Owner();
            owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[0][0].ToString());
            owner.Name = dSet.Tables[0].Rows[0][1].ToString();
            owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[0][2].ToString());
            owner.Phone = dSet.Tables[0].Rows[0][3].ToString();
            owner.BuildNum = dSet.Tables[0].Rows[0][4].ToString();
            owner.Unit = dSet.Tables[0].Rows[0][5].ToString();
            owner.RoomNum = dSet.Tables[0].Rows[0][6].ToString();
            conn.Close();
            return owner;
        }

        //通过id获得一个账户的信息,以DataSet数据类型返回
        public DataSet GetAnAccountByIndex_TO_DataSet(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE Oid={0}", index),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            return dSet;
        }
        public Owner GetAnAccountByIndex_TO_Owner(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE Oid={0}", index),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");

            Owner owner = new Owner();
            owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[0][0].ToString());
            owner.Name = dSet.Tables[0].Rows[0][1].ToString();
            owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[0][2].ToString());
            owner.Phone = dSet.Tables[0].Rows[0][3].ToString();
            owner.BuildNum = dSet.Tables[0].Rows[0][4].ToString();
            owner.Unit = dSet.Tables[0].Rows[0][5].ToString();
            owner.RoomNum = dSet.Tables[0].Rows[0][6].ToString();
            conn.Close();
            return owner;
        }


        //修改一行信息
        public void UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                    "UPDATE owner SET name=N'{0}',sex='{1}',phone=N'{2}',buildnum=N'{3}',unit=N'{4}',roomnum=N'{5}' " +
                    "WHERE Oid={6}; ", name, sex, phone, buildNum, unit, roomNum, index),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
        

        //删除一行信息
        public void DeleteAnAccount(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format("DELETE FROM owner WHERE Oid = {0}", index),
                conn);
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
    }
}

BLayer:

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

using YYYDemo.P_DLayer;
using System.Data;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗
using YYYDemo.Entity;

namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);

        public DataSet GetAllAccount_TO_DataSet()
        {
    
    
            return new DLayer().GetAllAccount_TO_DataSet();
        }
        public IList<Owner> GetAllAccount()
        {
    
    
            return new DLayer().GetAllAccount();
        }

        public void B_CloseConn()
        {
    
    
            new DLayer().D_CloseConn();
        }


        string errorStr = "";//这个也可以设置成局部变量,只不过让RegularCheck_Add(Update)_TO_Bool函数多传递一个参数而已。
        //添加账户时正则表达式对输入数据的验证
        private bool RegularCheck_Add_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";//2-4个中文
            string rStr_Phone = @"^\d{11}$";//11位数字
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";//1-3位数字

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            var owners = GetAllAccount();

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < owners.Count; i++)
            {
    
    

                if (phone == owners[i].Phone)
                    equal_Phone = true;

                if (
                    buildNum == owners[i].BuildNum &&
                    unit == owners[i].Unit &&
                    roomNum == owners[i].RoomNum
                    )
                    equal_Position = true;
            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }
            
            return flag;
        }
        
        //添加一个账户
        public string AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            if (RegularCheck_Add_TO_Bool(name, sex, phone, buildNum, unit, roomNum))
            {
    
    
                errorStr = "新增业主信息成功!";
                new DLayer().AddAnAccount(name, sex, phone, buildNum, unit, roomNum);
            }
            else
                errorStr += "\n新增业主信息失败!";
            return errorStr;
        }
        
        //通过手机号获取该行数据的索引,在U层中为下面的GetAnAccountByIndex_TO_DataSet()函数提供作用
        public int GetIndexByPhone_TO_Int(string phone)
        {
    
    
            return Convert.ToInt32(
                new DLayer().GetAnAccountByPhone_TO_Owner(phone).Oid);
            //return Convert.ToInt32(
                //new DLayer().GetAnAccountByPhone_TO_DataSet(phone).Tables[0].Rows[0][0].ToString());
        }
        
        //通过索引获取该行数据的全部信息,以DataSet数据类型返回
        public DataSet GetAnAccountByIndex_TO_DataSet(int index)
        {
    
    
            return new DLayer().GetAnAccountByIndex_TO_DataSet(index);
        }
        public Owner GetAnAccountBydIndex_TO_Owner(int index)
        {
    
    
            return new DLayer().GetAnAccountByIndex_TO_Owner(index);
        }
        
        //修改一个账户的信息
        public string UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            if (RegularCheck_Update_TO_Bool(name, sex, phone, buildNum, unit, roomNum, index))
            {
    
    
                errorStr = "修改业主信息成功!";
                new DLayer().UpdateAnAccount(name, sex, phone, buildNum, unit, roomNum, index);
            }
            else
                errorStr += "\n修改业主信息失败!";
            return errorStr;
        }
        //修改账户时正则表达式对输入数据的验证
        //修改个人信息,需要验证 手机号 和 住房位置 是否 *跟别人* 重复;还需验证数据是否合理
        private bool RegularCheck_Update_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";
            string rStr_Phone = @"^\d{11}$";
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }
            
            var owners = GetAllAccount();

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < owners.Count; i++)
            {
    
    
                if (owners[i].Oid != index)
                {
    
    
                    if (phone == owners[i].Phone)
                        equal_Phone = true;

                    if (
                        buildNum == owners[i].BuildNum &&
                        unit == owners[i].Unit &&
                        roomNum == owners[i].RoomNum
                        )
                        equal_Position = true;
                }

            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }
            
            return flag;
        }
        
        //删除一个账户
        public string DeleteAnAccount(int index)
        {
    
    
            errorStr = "删除业主信息成功!";
            new DLayer().DeleteAnAccount(index);
            return errorStr;
        }

    }
}

ShowAll.aspx.cs

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

using YYYDemo.P_BLayer;

namespace P_ULayer
{
    
    
    public partial class ShowAll : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            this.gView.DataSource = new BLayer().GetAllAccount();
            this.gView.DataBind();
        }

        protected void gView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
    
    
            if (e.CommandName == "Y_Update" || e.CommandName == "Y_Delete")
            {
    
    
                //获取 操作列 或者 删除列 点击的是GridView的哪一行
                int gViewSelect_Index = Convert.ToInt32(e.CommandArgument);
                //将点击的这一行的手机号(因为手机号不可重复)的业主的Oid字段的值传给 全局变量 Application["Index"] 
                Application["Index"] = new BLayer().GetIndexByPhone_TO_Int(
                    this.gView.Rows[gViewSelect_Index].Cells[2].Text.ToString()
                    );

                //这个代码块也就是实现了 : 点击的哪一行 ---> 手机号 ---> Oid ---> Application["Index"]
            }

            if (e.CommandName == "Y_Update")
                Response.Redirect("AlterAccount.aspx");

            if (e.CommandName == "Y_Delete")
            {
    
    
                if (BtnDelete() == 1)
                {
    
    
                    new BLayer().DeleteAnAccount(Convert.ToInt32(Application["Index"]));
                    Response.Redirect("ShowAll.aspx");
                }
            }
        }

        protected void gView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
    
    
            this.gView.PageIndex = e.NewPageIndex;
            gView.DataBind();
        }
        private int BtnDelete()
        {
    
    
            return BLayer.MessageBox(IntPtr.Zero, "确定要删除这条数据吗?", "警告!", 1);
        }
    }
}

Alteraccount.aspx.cs

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 YYYDemo.P_BLayer;
using YYYDemo.Entity;

namespace YYYDemo.P_ULayer
{
    
    
    public partial class WebForm2 : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            //这里若不加此判断,则每次点击未修改成功的按钮后,页面都会重传,然后恢复一开始的值,不会保存修改的值
            if (!IsPostBack)
            {
    
    
                Owner owner = new BLayer().GetAnAccountBydIndex_TO_Owner(Convert.ToInt32(Application["Index"]));
               
                (Master.FindControl("textBox_Name") as TextBox).Text = owner.Name;
                if (owner.Sex == '男')
                    (Master.FindControl("radioBtn_Boy") as RadioButton).Checked = true;
                if (owner.Sex == '女')
                    (Master.FindControl("radioBtn_Girl") as RadioButton).Checked = true;
                (Master.FindControl("textBox_Phone") as TextBox).Text = owner.Phone;
                (Master.FindControl("textBox_BuildNum") as TextBox).Text = owner.BuildNum;
                (Master.FindControl("textBox_Unit") as TextBox).Text = owner.Unit;
                (Master.FindControl("textBox_RoomNum") as TextBox).Text = owner.RoomNum;
                
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
    
    
            char sex = '男';
            if ((Master.FindControl("radioBtn_Girl") as RadioButton).Checked)
                sex = '女';


            string message = new BLayer().UpdateAnAccount(
                        (Master.FindControl("textBox_Name") as TextBox).Text.ToString(),
                        sex,
                        (Master.FindControl("textBox_Phone") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_BuildNum") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_Unit") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_RoomNum") as TextBox).Text.ToString(),
                        Convert.ToInt32(Application["index"])
                        );
            BLayer.MessageBox(IntPtr.Zero, message, "提示!", 0);
        }
    }
}

2. After deleting redundant code:

DLayer.cs
image.png

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

using System.Data;
using System.Data.SqlClient;
using YYYDemo.Entity;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }
        //获取全部的账户信息,以Owner实体类类型返回
        public IList<Owner> GetAllAccount()
        {
    
    
            List<Owner> owners = new List<Owner>();

            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
            {
    
    
                Owner owner = new Owner();
                owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[i][0].ToString());
                owner.Name = dSet.Tables[0].Rows[i][1].ToString();
                owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[i][2].ToString());
                owner.Phone = dSet.Tables[0].Rows[i][3].ToString();
                owner.BuildNum = dSet.Tables[0].Rows[i][4].ToString();
                owner.Unit = dSet.Tables[0].Rows[i][5].ToString();
                owner.RoomNum = dSet.Tables[0].Rows[i][6].ToString();
                owners.Add(owner);
            }
            conn.Close();
            return owners;
        }
        //添加一个账户
        public void AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                "INSERT INTO owner(name,sex,phone,buildnum,unit,roomnum) " +
                "VALUES(N'{0}','{1}',N'{2}',N'{3}',N'{4}',N'{5}')"
                , name, sex, phone, buildNum, unit, roomNum),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
        //通过手机号获得一个账户的信息,以Owner实体类类型返回;
        //这个函数是为了在B层通过手机号获取账户的id
        public Owner GetAnAccountByPhone_TO_Owner(string phone)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE phone=N'{0}'", phone),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");

            Owner owner = new Owner();
            owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[0][0].ToString());
            owner.Name = dSet.Tables[0].Rows[0][1].ToString();
            owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[0][2].ToString());
            owner.Phone = dSet.Tables[0].Rows[0][3].ToString();
            owner.BuildNum = dSet.Tables[0].Rows[0][4].ToString();
            owner.Unit = dSet.Tables[0].Rows[0][5].ToString();
            owner.RoomNum = dSet.Tables[0].Rows[0][6].ToString();
            conn.Close();
            return owner;
        }
        //通过id获得一个账户的信息,以Owner实体类类型返回
        public Owner GetAnAccountByIndex_TO_Owner(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE Oid={0}", index),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");

            Owner owner = new Owner();
            owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[0][0].ToString());
            owner.Name = dSet.Tables[0].Rows[0][1].ToString();
            owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[0][2].ToString());
            owner.Phone = dSet.Tables[0].Rows[0][3].ToString();
            owner.BuildNum = dSet.Tables[0].Rows[0][4].ToString();
            owner.Unit = dSet.Tables[0].Rows[0][5].ToString();
            owner.RoomNum = dSet.Tables[0].Rows[0][6].ToString();
            conn.Close();
            return owner;
        }
        //修改一行信息
        public void UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                    "UPDATE owner SET name=N'{0}',sex='{1}',phone=N'{2}',buildnum=N'{3}',unit=N'{4}',roomnum=N'{5}' " +
                    "WHERE Oid={6}; ", name, sex, phone, buildNum, unit, roomNum, index),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
        //删除一行信息
        public void DeleteAnAccount(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format("DELETE FROM owner WHERE Oid = {0}", index),
                conn);
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
    }
}

BLayer.cs
image.png

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

using YYYDemo.P_DLayer;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗
using YYYDemo.Entity;

namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);
        public IList<Owner> GetAllAccount()
        {
    
    
            return new DLayer().GetAllAccount();
        }
        string errorStr = "";//这个也可以设置成局部变量,只不过让RegularCheck_Add(Update)_TO_Bool函数多传递一个参数而已。
        //添加账户时正则表达式对输入数据的验证
        private bool RegularCheck_Add_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";//2-4个中文
            string rStr_Phone = @"^\d{11}$";//11位数字
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";//1-3位数字

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            var owners = GetAllAccount();

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < owners.Count; i++)
            {
    
    

                if (phone == owners[i].Phone)
                    equal_Phone = true;

                if (
                    buildNum == owners[i].BuildNum &&
                    unit == owners[i].Unit &&
                    roomNum == owners[i].RoomNum
                    )
                    equal_Position = true;
            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }
            
            return flag;
        }
        //添加一个账户
        public string AddAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum)
        {
    
    
            if (RegularCheck_Add_TO_Bool(name, sex, phone, buildNum, unit, roomNum))
            {
    
    
                errorStr = "新增业主信息成功!";
                new DLayer().AddAnAccount(name, sex, phone, buildNum, unit, roomNum);
            }
            else
                errorStr += "\n新增业主信息失败!";
            return errorStr;
        }
        //通过手机号获取该行数据的索引,在U层中为下面的GetAnAccountByIndex_TO_DataSet()函数提供作用
        public int GetIndexByPhone_TO_Int(string phone)
        {
    
    
            return Convert.ToInt32(
                new DLayer().GetAnAccountByPhone_TO_Owner(phone).Oid);
        }
        //通过索引获取该行数据的全部信息,以Owner实体类类型返回
        public Owner GetAnAccountBydIndex_TO_Owner(int index)
        {
    
    
            return new DLayer().GetAnAccountByIndex_TO_Owner(index);
        }
        //修改一个账户的信息
        public string UpdateAnAccount(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            if (RegularCheck_Update_TO_Bool(name, sex, phone, buildNum, unit, roomNum, index))
            {
    
    
                errorStr = "修改业主信息成功!";
                new DLayer().UpdateAnAccount(name, sex, phone, buildNum, unit, roomNum, index);
            }
            else
                errorStr += "\n修改业主信息失败!";
            return errorStr;
        }
        //修改账户时正则表达式对输入数据的验证
        //修改个人信息,需要验证 手机号 和 住房位置 是否 *跟别人* 重复;还需验证数据是否合理
        private bool RegularCheck_Update_TO_Bool(string name, char sex, string phone, string buildNum, string unit, string roomNum, int index)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";
            string rStr_Phone = @"^\d{11}$";
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";

            if (!Regex.IsMatch(name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(buildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(roomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }
            
            var owners = GetAllAccount();

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < owners.Count; i++)
            {
    
    
                if (owners[i].Oid != index)
                {
    
    
                    if (phone == owners[i].Phone)
                        equal_Phone = true;

                    if (
                        buildNum == owners[i].BuildNum &&
                        unit == owners[i].Unit &&
                        roomNum == owners[i].RoomNum
                        )
                        equal_Position = true;
                }

            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }
            
            return flag;
        }
        //删除一个账户
        public string DeleteAnAccount(int index)
        {
    
    
            errorStr = "删除业主信息成功!";
            new DLayer().DeleteAnAccount(index);
            return errorStr;
        }

    }
}

ShowAll.aspx.cs

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

using YYYDemo.P_BLayer;

namespace P_ULayer
{
    
    
    public partial class ShowAll : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            this.gView.DataSource = new BLayer().GetAllAccount();
            this.gView.DataBind();
        }

        protected void gView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
    
    
            if (e.CommandName == "Y_Update" || e.CommandName == "Y_Delete")
            {
    
    
                //获取 操作列 或者 删除列 点击的是GridView的哪一行
                int gViewSelect_Index = Convert.ToInt32(e.CommandArgument);
                //将点击的这一行的手机号(因为手机号不可重复)的业主的Oid字段的值传给 全局变量 Application["Index"] 
                Application["Index"] = new BLayer().GetIndexByPhone_TO_Int(
                    this.gView.Rows[gViewSelect_Index].Cells[2].Text.ToString()
                    );

                //这个代码块也就是实现了 : 点击的哪一行 ---> 手机号 ---> Oid ---> Application["Index"]
            }

            if (e.CommandName == "Y_Update")
                Response.Redirect("AlterAccount.aspx");

            if (e.CommandName == "Y_Delete")
            {
    
    
                if (BtnDelete() == 1)
                {
    
    
                    new BLayer().DeleteAnAccount(Convert.ToInt32(Application["Index"]));
                    Response.Redirect("ShowAll.aspx");
                }
            }
        }

        protected void gView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
    
    
            this.gView.PageIndex = e.NewPageIndex;
            gView.DataBind();
        }
        private int BtnDelete()
        {
    
    
            return BLayer.MessageBox(IntPtr.Zero, "确定要删除这条数据吗?", "警告!", 1);
        }
    }
}

AlterAccount.aspx.cs

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

using YYYDemo.P_BLayer;
using YYYDemo.Entity;

namespace YYYDemo.P_ULayer
{
    
    
    public partial class WebForm2 : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            //这里若不加此判断,则每次点击未修改成功的按钮后,页面都会重传,然后恢复一开始的值,不会保存修改的值
            if (!IsPostBack)
            {
    
    
                Owner owner = new BLayer().GetAnAccountBydIndex_TO_Owner(Convert.ToInt32(Application["Index"]));
               
                (Master.FindControl("textBox_Name") as TextBox).Text = owner.Name;
                if (owner.Sex == '男')
                    (Master.FindControl("radioBtn_Boy") as RadioButton).Checked = true;
                if (owner.Sex == '女')
                    (Master.FindControl("radioBtn_Girl") as RadioButton).Checked = true;
                (Master.FindControl("textBox_Phone") as TextBox).Text = owner.Phone;
                (Master.FindControl("textBox_BuildNum") as TextBox).Text = owner.BuildNum;
                (Master.FindControl("textBox_Unit") as TextBox).Text = owner.Unit;
                (Master.FindControl("textBox_RoomNum") as TextBox).Text = owner.RoomNum;
                
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
    
    
            char sex = '男';
            if ((Master.FindControl("radioBtn_Girl") as RadioButton).Checked)
                sex = '女';


            string message = new BLayer().UpdateAnAccount(
                        (Master.FindControl("textBox_Name") as TextBox).Text.ToString(),
                        sex,
                        (Master.FindControl("textBox_Phone") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_BuildNum") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_Unit") as TextBox).Text.ToString(),
                        (Master.FindControl("textBox_RoomNum") as TextBox).Text.ToString(),
                        Convert.ToInt32(Application["index"])
                        );
            BLayer.MessageBox(IntPtr.Zero, message, "提示!", 0);
        }
    }
}

Run the test, everything is normal

Note:

  1. After adding the entity class, modify the code of DLayer to modify the function with DataSet as the return value as the function you want to modify
  2. After modifying the code, make sure that except for the DLayer code in the D layer that has System.Data references, the rest of the layers have no

Delete the redundant Class1, the current structure is as shown in the figure below:
image.png


When the entity class is not applicable, the value of the DataField of the GridView column must correspond to the name of the field in the data table. If the structure of the data table is modified, the program will report an error.
Now after using the entity class, the value of the DataField in the GridView column of the U layer corresponds to the attribute name of the entity class. Although it has not changed here, it is because when I design the entity class, the attribute name of the entity class is modeled after It comes from the field name of the data table, so although the value of the DataField here has not changed, it has actually been mapped to the attribute name of the entity class, not the field name of the data table.
That is to say, for example, I change the name of the Name property of the entity class to MMMM, and then change all the places where the Name property of the entity class is used on the DLayer and AlterAccount pages to MMMM, and finally change the name of a column of the GridView on the ShowAll page to If the value of the DataField property is set to MMMM, the program will run normally.
image.png

2.14 Continue to modify the code, modify the formal parameters of the new and modified functions of the D layer to the Owner entity class object

D-level project:
modify a series of formal parameters to a parameter of Owner type
image.png

image.png

B-level project:
image.png

image.png

image.png

Similarly, modifying the AlterAccount function of the B layer also needs to change the formal parameters like the AddAccount function.
Next, I will not go to the picture, and directly put the current codes of the B layer and the D layer.

Layer B BLayer:

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

using YYYDemo.P_DLayer;
using System.Text.RegularExpressions;//正则表达式
using System.Runtime.InteropServices;//为了实现一个弹窗
using YYYDemo.Entity;

namespace YYYDemo.P_BLayer
{
    
    
    public class BLayer
    {
    
    
        //提示框,这两行照着写上即可,不必理解原理,会使用就行
        [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern int MessageBox(IntPtr handle, String message, String title, int type);
        public IList<Owner> GetAllAccount()
        {
    
    
            return new DLayer().GetAllAccount();
        }
        string errorStr = "";//这个也可以设置成局部变量,只不过让RegularCheck_Add(Update)_TO_Bool函数多传递一个参数而已。
        //添加账户时正则表达式对输入数据的验证
        private bool RegularCheck_Add_TO_Bool(Owner _owner)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";//2-4个中文
            string rStr_Phone = @"^\d{11}$";//11位数字
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";//1-3位数字

            if (!Regex.IsMatch(_owner.Name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.Phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.BuildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.Unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.RoomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }

            var owners = GetAllAccount();

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < owners.Count; i++)
            {
    
    

                if (_owner.Phone == owners[i].Phone)
                    equal_Phone = true;

                if (
                    _owner.BuildNum == owners[i].BuildNum &&
                    _owner.Unit == owners[i].Unit &&
                    _owner.RoomNum == owners[i].RoomNum
                    )
                    equal_Position = true;
            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }
            
            return flag;
        }
        //添加一个账户
        public string AddAnAccount(Owner owner)
        {
    
    
            if (RegularCheck_Add_TO_Bool(owner))
            {
    
    
                errorStr = "新增业主信息成功!";
                new DLayer().AddAnAccount(owner);
            }
            else
                errorStr += "\n新增业主信息失败!";
            return errorStr;
        }
        //通过手机号获取该行数据的索引,在U层中为下面的GetAnAccountByIndex_TO_DataSet()函数提供作用
        public int GetIndexByPhone_TO_Int(string phone)
        {
    
    
            return Convert.ToInt32(
                new DLayer().GetAnAccountByPhone_TO_Owner(phone).Oid);
        }
        //通过索引获取该行数据的全部信息,以Owner实体类类型返回
        public Owner GetAnAccountBydIndex_TO_Owner(int index)
        {
    
    
            return new DLayer().GetAnAccountByIndex_TO_Owner(index);
        }
        //修改账户时正则表达式对输入数据的验证
        //修改个人信息,需要验证 手机号 和 住房位置 是否 *跟别人* 重复;还需验证数据是否合理
        private bool RegularCheck_Update_TO_Bool(Owner _owner)
        {
    
    
            errorStr = "";
            bool flag = true;
            string rStr_Name = "^[\u4e00-\u9fa5]{2,4}$";
            string rStr_Phone = @"^\d{11}$";
            string rStr_BuildNum_Unit_RoomNum = @"^\d{1,3}$";

            if (!Regex.IsMatch(_owner.Name, rStr_Name))
            {
    
    
                errorStr += "姓名应为2-4个汉字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.Phone, rStr_Phone))
            {
    
    
                errorStr += "号码应为11位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.BuildNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "楼号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.Unit, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "单元号应为1-3位数字!\n";
                flag = false;
            }
            if (!Regex.IsMatch(_owner.RoomNum, rStr_BuildNum_Unit_RoomNum))
            {
    
    
                errorStr += "房间号应为1-3位数字!\n";
                flag = false;
            }
            
            var owners = GetAllAccount();

            bool equal_Phone = false;
            bool equal_Position = false;

            for (int i = 0; i < owners.Count; i++)
            {
    
    
                if (owners[i].Oid != _owner.Oid)
                {
    
    
                    if (_owner.Phone == owners[i].Phone)
                        equal_Phone = true;

                    if (
                        _owner.BuildNum == owners[i].BuildNum &&
                        _owner.Unit == owners[i].Unit &&
                        _owner.RoomNum == owners[i].RoomNum
                        )
                        equal_Position = true;
                }

            }
            if (equal_Phone)
            {
    
    
                errorStr += "联系电话不能重复!\n";
                flag = false;
            }
            if (equal_Position)
            {
    
    
                errorStr += "住房位置不能重复!\n";
                flag = false;
            }
            
            return flag;
        }
        //修改一个账户的信息
        public string UpdateAnAccount(Owner owner)
        {
    
    
            if (RegularCheck_Update_TO_Bool(owner))
            {
    
    
                errorStr = "修改业主信息成功!";
                new DLayer().UpdateAnAccount(owner);
            }
            else
                errorStr += "\n修改业主信息失败!";
            return errorStr;
        }
        //删除一个账户
        public string DeleteAnAccount(int index)
        {
    
    
            errorStr = "删除业主信息成功!";
            new DLayer().DeleteAnAccount(index);
            return errorStr;
        }

    }
}

D layer DLayer:

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

using System.Data;
using System.Data.SqlClient;
using YYYDemo.Entity;

namespace YYYDemo.P_DLayer
{
    
    
    public class DLayer
    {
    
    
        //创建数据库连接
        private SqlConnection CreateConnection()
        {
    
    
            return new SqlConnection(
                "Data Source=DESKTOP-ADKCETM;Initial Catalog=Y_strong;Integrated Security=True"
                );
        }
        //获取全部的账户信息,以Owner实体类类型返回
        public IList<Owner> GetAllAccount()
        {
    
    
            List<Owner> owners = new List<Owner>();

            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                "SELECT * FROM owner", conn
                );
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");
            for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
            {
    
    
                Owner owner = new Owner();
                owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[i][0].ToString());
                owner.Name = dSet.Tables[0].Rows[i][1].ToString();
                owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[i][2].ToString());
                owner.Phone = dSet.Tables[0].Rows[i][3].ToString();
                owner.BuildNum = dSet.Tables[0].Rows[i][4].ToString();
                owner.Unit = dSet.Tables[0].Rows[i][5].ToString();
                owner.RoomNum = dSet.Tables[0].Rows[i][6].ToString();
                owners.Add(owner);
            }
            conn.Close();
            return owners;
        }
        //添加一个账户
        public void AddAnAccount(Owner owner)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                "INSERT INTO owner(name,sex,phone,buildnum,unit,roomnum) " +
                "VALUES(N'{0}','{1}',N'{2}',N'{3}',N'{4}',N'{5}')"
                , owner.Name, owner.Sex, owner.Phone, owner.BuildNum, owner.Unit, owner.RoomNum),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
        //通过手机号获得一个账户的信息,以Owner实体类类型返回;
        //这个函数是为了在B层通过手机号获取账户的id
        public Owner GetAnAccountByPhone_TO_Owner(string phone)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE phone=N'{0}'", phone),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");

            Owner owner = new Owner();
            owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[0][0].ToString());
            owner.Name = dSet.Tables[0].Rows[0][1].ToString();
            owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[0][2].ToString());
            owner.Phone = dSet.Tables[0].Rows[0][3].ToString();
            owner.BuildNum = dSet.Tables[0].Rows[0][4].ToString();
            owner.Unit = dSet.Tables[0].Rows[0][5].ToString();
            owner.RoomNum = dSet.Tables[0].Rows[0][6].ToString();
            conn.Close();
            return owner;
        }
        //通过id获得一个账户的信息,以Owner实体类类型返回
        public Owner GetAnAccountByIndex_TO_Owner(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            conn.Open();
            SqlDataAdapter dAdp = new SqlDataAdapter(
                string.Format("SELECT * FROM owner WHERE Oid={0}", index),
                conn);
            DataSet dSet = new DataSet();
            dAdp.Fill(dSet, "owner");

            Owner owner = new Owner();
            owner.Oid = Convert.ToInt32(dSet.Tables[0].Rows[0][0].ToString());
            owner.Name = dSet.Tables[0].Rows[0][1].ToString();
            owner.Sex = Convert.ToChar(dSet.Tables[0].Rows[0][2].ToString());
            owner.Phone = dSet.Tables[0].Rows[0][3].ToString();
            owner.BuildNum = dSet.Tables[0].Rows[0][4].ToString();
            owner.Unit = dSet.Tables[0].Rows[0][5].ToString();
            owner.RoomNum = dSet.Tables[0].Rows[0][6].ToString();
            conn.Close();
            return owner;
        }
        //修改一行信息
        public void UpdateAnAccount(Owner owner)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format(
                    "UPDATE owner SET name=N'{0}',sex='{1}',phone=N'{2}',buildnum=N'{3}',unit=N'{4}',roomnum=N'{5}' " +
                    "WHERE Oid={6}; ", owner.Name, owner.Sex, owner.Phone, owner.BuildNum, owner.Unit, owner.RoomNum, owner.Oid),
                conn
                );
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
        //删除一行信息
        public void DeleteAnAccount(int index)
        {
    
    
            SqlConnection conn = CreateConnection();
            SqlCommand cmd = new SqlCommand(
                string.Format("DELETE FROM owner WHERE Oid = {0}", index),
                conn);
            try
            {
    
    
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
    
    
                throw e;
            }
            finally
            {
    
    
                conn.Close();
            }
        }
    }
}

Modify the code of the new and modified part of the U layer:
image.png

image.png

AddAccount.aspx.cs

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

using YYYDemo.P_BLayer;
using YYYDemo.Entity;

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

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
    
    
            char sex = '男';
            if ((Master.FindControl("radioBtn_Girl") as RadioButton).Checked)
                sex = '女';

            Owner owner = new Owner();

            owner.Name = (Master.FindControl("textBox_Name") as TextBox).Text.ToString();
            owner.Sex = sex;
            owner.Phone = (Master.FindControl("textBox_Phone") as TextBox).Text.ToString();
            owner.BuildNum = (Master.FindControl("textBox_BuildNum") as TextBox).Text.ToString();
            owner.Unit = (Master.FindControl("textBox_Unit") as TextBox).Text.ToString();
            owner.RoomNum = (Master.FindControl("textBox_RoomNum") as TextBox).Text.ToString();

            string message = new BLayer().AddAnAccount(owner);
            BLayer.MessageBox(IntPtr.Zero, message, "提示!", 0);
        }
    }
}

AlterAccount.aspx.cs

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

using YYYDemo.P_BLayer;
using YYYDemo.Entity;

namespace YYYDemo.P_ULayer
{
    
    
    public partial class WebForm2 : System.Web.UI.Page
    {
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            //这里若不加此判断,则每次点击未修改成功的按钮后,页面都会重传,然后恢复一开始的值,不会保存修改的值
            if (!IsPostBack)
            {
    
    
                Owner owner = new BLayer().GetAnAccountBydIndex_TO_Owner(Convert.ToInt32(Application["Index"]));
               
                (Master.FindControl("textBox_Name") as TextBox).Text = owner.Name;
                if (owner.Sex == '男')
                    (Master.FindControl("radioBtn_Boy") as RadioButton).Checked = true;
                if (owner.Sex == '女')
                    (Master.FindControl("radioBtn_Girl") as RadioButton).Checked = true;
                (Master.FindControl("textBox_Phone") as TextBox).Text = owner.Phone;
                (Master.FindControl("textBox_BuildNum") as TextBox).Text = owner.BuildNum;
                (Master.FindControl("textBox_Unit") as TextBox).Text = owner.Unit;
                (Master.FindControl("textBox_RoomNum") as TextBox).Text = owner.RoomNum;
                
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
    
    
            char sex = '男';
            if ((Master.FindControl("radioBtn_Girl") as RadioButton).Checked)
                sex = '女';

            Owner owner = new Owner();

            owner.Oid = Convert.ToInt32(Application["index"]);
            owner.Name = (Master.FindControl("textBox_Name") as TextBox).Text.ToString();
            owner.Sex = sex;
            owner.Phone = (Master.FindControl("textBox_Phone") as TextBox).Text.ToString();
            owner.BuildNum = (Master.FindControl("textBox_BuildNum") as TextBox).Text.ToString();
            owner.Unit = (Master.FindControl("textBox_Unit") as TextBox).Text.ToString();
            owner.RoomNum = (Master.FindControl("textBox_RoomNum") as TextBox).Text.ToString();

            string message = new BLayer().UpdateAnAccount(owner);
            BLayer.MessageBox(IntPtr.Zero, message, "提示!", 0);
        }
    }
}

Run, test functionality, no problem.


dividing line two

So far, the entity class has been implemented.

May 22, 2019 23:39:08


Guess you like

Origin blog.csdn.net/qq_41286942/article/details/101980776