Saturday, 14 February 2015

Working with 3- Tier Architecture in C#


  Introduction


In this article we will learn Use to 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and well known in world of software development. If we analyze any traditional project We used 3-Tier Architecture. It does not matter whether it is web or windows application, we can implement 3-Tier architecture in any type of development environment.


It is N-Tier architecture. So, we can create as much layer as possible but mostly developer code in three different categories and put them in three different layers. So, we try to  N-Tier architecture as 3-Tier architecture and try to implement one sample application.

 

Presentation Layer or UI Layer


This is the top most layer of application where user performs their activity.If any application where user needs to fill up one form. This form is  presentation layer. In windows application windows form is presentation layer and in web application web form belongs to presentation layer. Basically user’s input validation,Controls and rule processing performs in this layer.
 

Business Layer


This is on top of presentation layer. As the name suggest, most of the business operation performs here. Like, after collecting form data we want to validate them with our custom business rule. Basically we define classes and business entities in this layer.

 

Data Access Layer


It is the top of Business Logic Layer Data Access Layer presents. It contains methods & Functions that helps business layer to connect with database and perform operations. In data access layer generally all database related code and it perform all database activity to manage the application

Code for Data Access Layer

 Data access layer; we will create function to read data from database.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1.DAL
{
    public class PersonDAL
    {
        public string ConString = 
            "Data Source=MANISH-PC\\SQLEXPRESS;Initial Catalog=test;Integrated
 Security=True";
        SqlConnection con = new SqlConnection();
        DataTable dt = new DataTable();
        public DataTable Read()
        {
            con.ConnectionString = ConString;
            if (ConnectionState.Closed == con.State)
                con.Open();
            SqlCommand cmd = new SqlCommand("select * from Employe",con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }
        public DataTable Read(Int16 Id)
        {
            con.ConnectionString = ConString;
            if (ConnectionState.Closed == con.State)
                con.Open();
            SqlCommand cmd = new SqlCommand("select * from Employe where 
ID= "+ Id +"", con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }
    }
}

Create Business Logic Layer

Now, we will create Business Logic Layer to communication with both Presentation layer and Data access layer.


using System;
using System.Collections.Generic;
using System.Data;
using WindowsFormsApplication1.DAL;
 
namespace WindowsFormsApplication1.BLL
{
    public class PersonBLL
    {
        public DataTable GetPersons()
        {
            try
            {
                PersonDAL objdal = new PersonDAL();
                return objdal.Read();
            }
            catch
            {
                throw;
            }
        }
        public DataTable GetPersons(Int16 ID)
        {
            try
            {
                PersonDAL objdal = new PersonDAL();
                return objdal.Read(ID);
            }
            catch
            {
                throw;
            }
        }
       
    }
}

Create Presentation Layer.

This is the top most layer where user will interact with system. We will create simple windows for like this.








using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication1.BLL;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                PersonBLL p = new PersonBLL();
                this.dataGridView1.DataSource = p.GetPersons(Convert.ToInt16
(this.txtID.Text));
            }
            catch
            {
                MessageBox.Show("Error Occurred");
            }
        }
 
        private void Form1_Load(object sender, EventArgs e)
        { 
            try
            {
                PersonBLL p = new PersonBLL();
                this.dataGridView1.DataSource = p.GetPersons();
            }
            catch
            {
                MessageBox.Show("Error Occurred");
            }
        }
    }
}




Folder structure in solution explorer

Here is our sample folder stricture in solution explorer. We have created all layers in same solution.


Thursday, 12 February 2015

Edit Update Multiple Rows in ASP.Net GridView using CheckBoxes

Bulk Edit Update Multiple Rows in ASP.Net GridView using CheckBoxes

How to Bulk Edit Update Multiple Rows or records in ASP.Net GridView at once using CheckBoxes on single click. In this example he has explained how we can use TextBox and DropDownList in Edit mode.
In this article I will explain how to edit and update multiple rows in ASP.Net GridView using CheckBoxes i.e. the Rows which are checked will become editable and user can update multiple rows on one single Update button click.


HTML PAGE  CODE:


<asp:GridView ID="grvEmploye" runat="server" AutoGenerateColumns="false" 
OnRowDataBound = "OnRowDataBound" DataKeyNames ="empId">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox ID = "chkAll" runat="server" AutoPostBack=
"true" OnCheckedChanged="OnCheckedChanged" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label runat="server" Text='<%# Eval("Name")%>'></asp:Label>
 <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Name")%>'
 Visible="false"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label ID = "lblCountry" runat="server" Text='<%# Eval("CountryName") %>'></asp:Label>
                <asp:DropDownList ID="ddlCountry" runat="server" Visible = "false">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUpdt" runat="server" Text="Update" OnClick = "Update"
 Visible = "false"/>



Binding the ASP.Net GridView
Below is the code to bind the ASP.Net GridView control with records from the Employe table of the My_Demo database.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}
private void BindGrid()
string sql="SELECT empId, Name, Country FROM Employe"
    SqlCommand cmd = new SqlCommand(sql);


 DataTable dt = new DataTable();
        SqlDataAdapter ada = new SqlDataAdapter(cmd);
        ada.Fill(dt);
        grvEmploye.DataSource = dt;
        grvEmploye.DataBind();

}


Fill the Country DropDownList in the ASP.Net GridView Row
In the OnRowDataBound event of the ASP.Net GridView I am populating the Country DropDownList which will be displayed when a row is edited.



protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        SqlCommand cmd = new SqlCommand("SELECT DISTINCT(Country) FROM Employe");
        DropDownList ddlCountry= (e.Row.FindControl("ddlCountry"as DropDownList);
        ddlCountry.DataSource = this.ExecuteQuery(cmd, "SELECT");
        ddlCountry.DataTextField = "Country";
        ddlCountry.DataValueField = "Country";
        ddlCountry.DataBind();
        string country = (e.Row.FindControl("lblCountry"as Label).Text;
        ddlCountry.Items.FindByValue(country).Selected = true;
    }
}



Change the ASP.Net GridView Row to Edit mode on CheckBox checked
The below event handler is executed when the CheckBox is the ASP.Net GridView Row is checked or unchecked all.
 looping through the GridView Rows and checking whether the CheckBox is checked for that Row. If the CheckBox is checked then the Label control in the GridView Cell is hidden and the corresponding TextBox or DropDownList is made visible.
the Update button btnUpdate is only visible when at least 1 checkbox is checked true.

protected void OnCheckedChanged(object sender, EventArgs e)
{
    bool isUpdateVisible = false;
    CheckBox chk = (sender as CheckBox);
    if (chk.ID == "chkAll")
    {
        foreach (GridViewRow row in grvEmploye.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
            }
        }
    }
    CheckBox chkAll = (gvCustomers.HeaderRow.FindControl("chkAll"as CheckBox);
    chkAll.Checked = true;
    foreach (GridViewRow row in grvEmploye.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
            for (int i = 1; i < row.Cells.Count; i++)
            {
                row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
                if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
                {
                    row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
                }
                if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
                {
                    row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
                }
                if (isChecked && !isUpdateVisible)
                {
                    isUpdateVisible = true;
                }
                if (!isChecked )
                {
                    chkAll.Checked = false;
                }
            }
        }
    }
    btnUpdate.Visible = isUpdateVisible;
}



Updating the edited records in ASP.Net GridView Row
The below event handler is executed when the Update button btnUpdate is clicked.

protected void Update(object sender, EventArgs e)
{
    foreach (GridViewRow row in grvEmploye.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
            if (isChecked)
            {
                SqlCommand cmd = new SqlCommand("UPDATE Employe SET Name = '"+ (row.Cells[1].Controls.OfType<TextBox>().FirstOrDefault().Text) +"', Country = '"+ (row.Cells[1].Controls.OfType<DropDownList>().FirstOrDefault().SelectedItem.Value) +"' WHERE empId = '"+grvEmploye.DataKeys[row.RowIndex].Value+"'");
cmd.ExecuteNonQuery();

               
            }
        }
    }
    btnUpdate.Visible = false;
    BindGrid();
}









Working with 3- Tier Architecture in C#

  Introduction In this article we will learn Use to 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and ...