【问题标题】:how to CRUD operation in gridview using 3 tier如何使用 3 层在 gridview 中进行 CRUD 操作
【发布时间】:2016-09-16 09:17:00
【问题描述】:

我正在使用 n 层架构 这是我的 aspx.cs 代码

using System;
using System.Web.UI;
using BAL;
using System.Web.UI.WebControls;

namespace GridViewThreeTierApplication
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrid();
            }
        }
        protected void BindGrid()
        {

            var dataSource = new DAL.dal().GetAllCustomers();
            if (dataSource != null)
            {
                GridView1.DataSource = dataSource;
                GridView1.DataBind();

            }

        }

        protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Control control = e.Row.Cells[0].Controls[0];
                if (control is LinkButton)
                {
                    int num = Convert.ToInt32(e.Row.RowIndex);
                    bal.DeleteCustomers(num);
                }

            }
        }

    }
}

这是我的标记

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" OnDataBound="GridView1_DataBound">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:TemplateField ShowHeader="False">
                        <EditItemTemplate>
                            <asp:Button ID="LinkButton1" runat="server" Text="Update" CommandName="Update" CausesValidation="true" />
                            &nbsp; <asp:Button ID="LinkButton2" runat="server" Text="Cancel" CausesValidation="false" CommandName="Cancel" />
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
                            &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CustomerID" SortExpression="CustomerID">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:Button ID="InsertBtn" runat="server" Text="Insert" />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtFname" runat="server"></asp:TextBox>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="LastName" SortExpression="LastName">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtFiname" runat="server"></asp:TextBox>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Email" SortExpression="Email">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtLname" runat="server"></asp:TextBox>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="PhoneNumber" SortExpression="PhoneNumber">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtFirname" runat="server"></asp:TextBox>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:CommandField />
                </Columns>
                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                <SortedAscendingCellStyle BackColor="#FDF5AC" />
                <SortedAscendingHeaderStyle BackColor="#4D0000" />
                <SortedDescendingCellStyle BackColor="#FCF6C0" />
                <SortedDescendingHeaderStyle BackColor="#820000" />
            </asp:GridView>

        </div>
    </form>
</body>
</html>

这是我的数据访问层

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;



namespace DAL
{
    public class dal
    {

        public class Customer
        {
            public int CustomerID { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Email { get; set; }
            public int PhoneNumber { get; set; }
        }

            public List<Customer> GetAllCustomers()
            {
                List<Customer> listCustomers = new List<Customer>();

                string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(CS))
                {
                    SqlCommand cmd = new SqlCommand("Select * from Customer", con);
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Customer Customer = new Customer();
                        Customer.CustomerID = Convert.ToInt32(rdr["CustomerID"]);
                        Customer.FirstName = rdr["FirstName"].ToString();
                        Customer.LastName = rdr["LastName"].ToString();
                        Customer.Email = rdr["Email"].ToString();
                        Customer.PhoneNumber = Convert.ToInt32(rdr["PhoneNumber"]);

                        listCustomers.Add(Customer);
                    }
                }

                return listCustomers;
            }

    }
}

这是我的业务对象

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

namespace BAL
{
    public class bal
    {
        protected void GetALLCustomer()
        {
        }

        public static void DeleteCustomers(int CustomerID)
        {
            string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
                SqlCommand cmd = new SqlCommand ("Delete from Customer where CustomerID = @CustomerID", con);
                SqlParameter param = new SqlParameter("@CustomerId", CustomerID);
                cmd.Parameters.Add(param);
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }


        public static int InsertCustomers(string FirstName, string LastName, string Email, int PhoneNumber)
        {
            string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
                string updateQuery = "Insert into Customers (FirstName, LastName, Email,PhoneNumber)" +
                    " values (@FirstName, @LastName, @Email,@PhoneNumber)";
                SqlCommand cmd = new SqlCommand(updateQuery, con);
                SqlParameter paramFirstName = new SqlParameter("@FirstName", FirstName);
                cmd.Parameters.Add(paramFirstName);
                SqlParameter paramLastName = new SqlParameter("@LastName", LastName);
                cmd.Parameters.Add(paramLastName);
                SqlParameter paramEmail = new SqlParameter("@Email", Email);
                cmd.Parameters.Add(paramEmail);
                SqlParameter paramPhoneNumber = new SqlParameter("@PhoneNumber", PhoneNumber);
                con.Open();
                return cmd.ExecuteNonQuery();
            }
        }
    }
}

我能够执行选择查询。 我无法执行创建、删除或更新。

【问题讨论】:

  • 您的业务层中不应有任何 ADO.NET 数据库调用。此外,如果您只做 CRUD,则不需要 BLL。
  • 是的,但我想要一个 3 层或 n 层应用程序

标签: c# asp.net gridview n-tier-architecture 3-tier


【解决方案1】:

cmd命令中好像没有电话号码参数

【讨论】:

    【解决方案2】:

    这是我的工作方式

    1) 首先我删除了事件 GridView1_DataBound 从 GridView1 中删除“CommandField”列(标记)

    <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
    

    2) 在其位置插入此标记

    <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="lbEdit" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="EditRow" ForeColor="#8C4510" runat="server">Edit</asp:LinkButton>
            <asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false">Delete</asp:LinkButton>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:LinkButton ID="lbUpdate" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="UpdateRow" ForeColor="#8C4510" runat="server">Update</asp:LinkButton>
            <asp:LinkButton ID="lbCancel" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="CancelUpdate" ForeColor="#8C4510" runat="server" CausesValidation="false">Cancel</asp:LinkButton>
        </EditItemTemplate>
    </asp:TemplateField>
    

    3) 插入 EmployeeId 的 FooterTemplate

    插入

    4) 现在生成 GridView1_RowCommand() 事件处理方法。

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditRow")
        {
            int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
            GridView1.EditIndex = rowIndex;
            BindGrid();
        }
        else if (e.CommandName == "DeleteRow")
        {
            BAL.bal.DeleteCustomers(Convert.ToInt32(e.CommandArgument));
            BindGrid();
        }
        else if (e.CommandName == "CancelUpdate")
        {
            GridView1.EditIndex = -1;
            BindGrid();
        }
        else if (e.CommandName == "UpdateRow")
        {
            int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
    
            int CustomerId = Convert.ToInt32(e.CommandArgument);
            string Name = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox1")).Text;
            string Gender = ((DropDownList)GridView1.Rows[rowIndex].FindControl("DropDownList1")).SelectedValue;
            string City = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox3")).Text;
    
            BAL.bal.UpdateCustomers(CustomerId, Name, Gender, City);                    
            GridView1.EditIndex = -1;
            BindGrid();
        }
        else if (e.CommandName == "InsertRow")
        {
            string Name = ((TextBox)GridView1.FooterRow.FindControl("txtName")).Text;
            string Gender = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
            string City = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
    
            BAL.bal.InsertCustomers(name, gender, city);
    
            BindGrid();
        }
    }
    

    6) 正确的 insertCustomer 方法

    public static int InsertCustomers(string Name, string Gender, string City)
            {
                string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlConnection con = new SqlConnection(CS))
                {
                    string updateQuery = "Insert into tblEmployee (Name, Gender, City)" +
                        " values (@Name, @Gender, @City)";
                    SqlCommand cmd = new SqlCommand(updateQuery, con);
                    SqlParameter paramName = new SqlParameter("@Name", Name);
                    cmd.Parameters.Add(paramName);
                    SqlParameter paramGender = new SqlParameter("@Gender", Gender);
                    cmd.Parameters.Add(paramGender);
                    SqlParameter paramCity = new SqlParameter("@City", City);
                    cmd.Parameters.Add(paramCity);
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
    

    如果要显示确认对话框,在删除一行之前,请包含 javascript confirm() 函数,使用 LinkBut​​ton "lbDelete" 的 "OnClientClick" 属性。

    <asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this row');">Delete</asp:LinkButton> 
    

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2016-04-09
      相关资源
      最近更新 更多