如何使用3层在gridview中进行CRUD操作

时间:2016-05-19 13:06:16

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

我正在使用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();
            }
        }
    }
}

我可以执行选择查询。 我无法执行创建,删除或更新。

2 个答案:

答案 0 :(得分:0)

似乎电话号码参数不在cmd命令

答案 1 :(得分:0)

以下是我如何开始工作

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();
            }
        }

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

<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>