2016-05-19 46 views
1

Я использую п уровневую архитектуру Вот мой aspx.cs кодкак Crud операции в GridView с использованием 3 яруса

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

Я могу выполнить запрос выбора. Я не могу выполнить создание, удаление или обновление.

+0

У вас не должно быть вызовов базы данных ADO.NET на вашем бизнес-уровне. Также, если вы делаете только CRUD, вам не нужен BLL. –

+0

Да, я понял, что, но мне нужно приложение с 3 уровнями или n уровнями – Khalil

ответ

0

Похоже параметра номер телефона не на CMD команды

0

Вот как я получил его на работу

1) Во-первых я удалил событие GridView1_DataBound колонке Delete «CommandField» из GridView1 (разметки)

<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) вставить эту FooterTemplate из EmployeeID

Вставка

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

Если вы хотите, чтобы показать диалоговое окно подтверждения, перед тем как строка будет удалена, включают яваскрипт Confirm() функцию, используя "OnClientClick" атрибут LinkButton " lbDelete».

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

 Смежные вопросы

  • Нет связанных вопросов^_^