Saturday, 30 August 2014

how to change password in C#

private void btnOk_Click(object sender, EventArgs e)
        {
            if (txtCurPass.Text != "")
            {
                if (Password() != txtCurPass.Text)
                {
                    MessageBox.Show("Incorrect Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtCurPass.Focus();
                    txtCurPass.SelectAll();
                    return;
                }
                if (txtNewPass.Text.Trim() != "")
                {
                    if (txtConPass.Text.Trim() != "")
                    {
                        if (txtNewPass.Text.Trim() == txtConPass.Text.Trim())
                        {
                            string str = "Update T_LoginMain Set pw='" + txtConPass.Text.Trim() + "' Where username=" + "'" + txtUsername.Text.Trim() + "'";
                            con = new OleDbConnection(dbCon());
                            OleDbCommand cmd = new OleDbCommand(str, con);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                            MessageBox.Show("Password Changed", "Changed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            TextClear();
                            this.Hide();
                        }
                        else
                        {
                            MessageBox.Show("New Password and Confirm Password must be same", "Same Password?", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtNewPass.Focus();
                            txtNewPass.SelectAll();
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Enter Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtConPass.Focus();
                        txtConPass.Focus();
                        txtConPass.SelectAll();
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Enter Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNewPass.Focus();
                    txtNewPass.SelectAll();
                    return;
                }
            }
            else
            {
                MessageBox.Show("Enter Current Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCurPass.Focus();
                txtCurPass.SelectAll();
                return;

            }

        }

how to create new user account in C#

    if (txtUsername.Text.TrimStart () != "")
            {
                if (txtNewPass.Text.TrimStart () != "")
                {
                    if (txtConPass.Text.TrimStart () != "")
                    {
                        if (txtNewPass.Text.TrimStart () == txtConPass.Text.TrimStart ())
                        {
                            string str = "Insert into T_LoginMain(username,pw,usertype)Values('" + txtUsername.Text.TrimStart () + "','" + txtConPass.Text.TrimStart () + "','" + cbxUserType.Text.TrimStart () + "')";
                            con = new OleDbConnection(dbCon());
                            OleDbCommand cmd = new OleDbCommand(str, con);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                            MessageBox.Show("User Created", "Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            TextClear();
                        }
                        else
                        {
                            MessageBox.Show("New Password and Confirm Password must be same", "Same Password?", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtNewPass.Focus();
                            txtNewPass.SelectAll();
                            return;
                        }

                    }
                    else
                    {
                        MessageBox.Show("Enter Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtConPass.Focus();
                        txtConPass.SelectAll();
                        return;
                    }

                }
                else
                {
                    MessageBox.Show("Enter Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNewPass.Focus();
                    txtNewPass.SelectAll();
                    return;
                }
            }
            else
            {
                MessageBox.Show("Enter Username", "Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUsername.Focus();
                txtUsername.SelectAll();
                return;
            }

how to get mac address in C#.Net

  public static string GetMacAddress()
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            String sMacAddress = string.Empty;
            foreach (NetworkInterface adapter in nics)
            {
                if (sMacAddress == String.Empty)// only return MAC Address from first card
                {
                    IPInterfaceProperties properties = adapter.GetIPProperties();
                    sMacAddress = adapter.GetPhysicalAddress().ToString();
                }
            } return sMacAddress;

        }

Wednesday, 20 August 2014

How to select credit,Debit and Balance Code for Crystal report viewer using formula feild





write this code in formula feild and Select Basic Syntax



//// working ==================


Global Bal As number
if {T_Statement.Debit}=0 then
Bal={T_Statement.Credit}+Bal
else
Bal=Bal-{T_Statement.Debit}
end if
formula = Bal



Tuesday, 19 August 2014

Mdi forms in C#

 FrmRptStatement obRptStatement = new FrmRptStatement();
            obRptStatement.MdiParent = this;
            obRptStatement.Show();

how to hide a form in mdiparent in C#

form closing event write this


            e.Cancel = true;
            this.Hide();
  

Crystal Report show

    // Report Source
            ds.Clear();
            string str1 = "Select * from T_ReportTotal Where ID=1";
            OleDbDataAdapter ada = new OleDbDataAdapter(str1, con);
            ada.Fill(ds, "T_ReportTotal");
            cr1.Refresh();
            cr1.SetDataSource(ds);
            progressBar1.SendToBack();
            progressBar1.Visible = false;
            crystalReportViewer1.Visible = true;
            crystalReportViewer1.ReportSource = cr1;
            cr1.SetParameterValue("From", dtpFrTotsale.Text);
            cr1.SetParameterValue("To", dtpToTotsale.Text);
            Cursor.Current = Cursors.Default;
            crystalReportViewer1.Cursor = Cursors.Default;
            con.Close();

Thursday, 14 August 2014

how to restrict minimum char in C#

   private void txtInvoiceNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtInvoiceNo.Text.Length > 29 && e.KeyChar != 8)
            {
                LOCK(sender, e);
                MessageBox.Show("30 Charactors Allowed", "Exceeding 30 Charactors");
            }
        }

how to remove datagridview rows in C#

  private void dgvPurchase_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                int selRow = dgvPurchase.Rows.GetFirstRow(DataGridViewElementStates.Selected);
                {
                    if (selRow > -1)
                    {
                        cbxMname.Text = dgvPurchase[1, selRow].Value.ToString();
                        cbxItemName.Text = dgvPurchase[2, selRow].Value.ToString();
                        cbxBatchNo .Text = dgvPurchase[3, selRow].Value.ToString();
                        dtpExpdate.Text = dgvPurchase[4, selRow].Value.ToString();
                        txtNosPBox .Text = dgvPurchase[5, selRow].Value.ToString();
                        txtTotBox.Text = dgvPurchase[6, selRow].Value.ToString();
                        txtFreeQty.Text = dgvPurchase[7, selRow].Value.ToString();
                        txtNetQty.Text = dgvPurchase[8, selRow].Value.ToString();
                        txtMrp.Text = dgvPurchase[9, selRow].Value.ToString();
                        txtDiscoPers.Text = dgvPurchase[10, selRow].Value.ToString();
                     
                        txtShopMorgin .Text = dgvPurchase[17, selRow].Value.ToString();
                        txtNetRate .Text = dgvPurchase[16, selRow].Value.ToString();
                        txtMarginamt.Text = dgvPurchase[18, selRow].Value.ToString();
                        txtBasicRate .Text = dgvPurchase[12, selRow].Value.ToString();
                        txtVatPers .Text = dgvPurchase[13, selRow].Value.ToString();
                        //txtPurTotAmount.Text = dgvPurchase[11, selRow].Value.ToString();
                        txtnetwp.Text = dgvPurchase[22, selRow].Value.ToString();
                        txtmrpwpval.Text = dgvPurchase[21, selRow].Value.ToString();
                       
                        cbxUnits.Text = dgvPurchase[25, selRow].Value.ToString();
                        txtMaxQty.Text = dgvPurchase[23, selRow].Value.ToString();
                        txtMinQty.Text = dgvPurchase[24, selRow].Value.ToString();
                        txttotqty.Text = dgvPurchase[26, selRow].Value.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Uncommitted Row Selectin", "Invalid Selection", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                dgvPurchase.ClearSelection();
            }
        }

how to load DB datas to Datagridview in C#

 private void SeltoDG()
        {
            try
            {
                ClsBEPurDetails bedg = new ClsBEPurDetails();

                string str = "Select SlNo,Mname,ItemName,BatchNo,ExpDate,ItemsPbox,TotalBox,FreeQty,NetQty,MRP,DiscPers,DiscAmt,Basicrate,VatPers,VatAmt,TransPers,Netcost,SellPrice,SellingMargin,SellingAmt,DummyRate,MRPValue,WPValue,MaxQty,MinQty,Units,Strength,AgsSubNet,Claim from T_PurDetails Where ID=" + cbxID.Text;
                dgvPurchase.Rows.Clear();
                con = new OleDbConnection(dbCon());
                OleDbCommand cmd = new OleDbCommand(str, con);
                con.Open();
                OleDbDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    bedg.SlNo = dr.GetValue(0).ToString();
                    bedg.PrType = dr.GetValue(1).ToString();
                    bedg.ItemName = dr.GetValue(2).ToString();
                    bedg.BatchNo = dr.GetValue(3).ToString();
                    bedg.ExpDte = dr.GetValue(4).ToString();
                    bedg.Nounit = dr.GetValue(5).ToString();
                    bedg.TotUnit = dr.GetValue(6).ToString();
                    bedg.FreeQty = dr.GetValue(7).ToString();
                    bedg.NetQty = dr.GetValue(8).ToString();
                    bedg.Mrp = dr.GetValue(9).ToString();
                    bedg.DiscPers = dr.GetValue(10).ToString();
                    bedg.Discamt = dr.GetValue(11).ToString();

                    bedg.BasicRate = dr.GetValue(12).ToString();
                    bedg.VatPers = dr.GetValue(13).ToString();
                    bedg.VatAmt = dr.GetValue(14).ToString();
                    bedg.TransPers = dr.GetValue(15).ToString();
                    bedg.Netcost = dr.GetValue(16).ToString();
                    bedg.SellingPers = dr.GetValue(17).ToString();
                    bedg.SellingMargin = dr.GetValue(18).ToString();
                    bedg.SellingAmt = dr.GetValue(19).ToString();
                    bedg.DummyRate = dr.GetValue(20).ToString();
                    bedg.MrpValue = dr.GetValue(21).ToString();
                    bedg.WpValue = dr.GetValue(22).ToString();
                    bedg.Maxqty = dr.GetValue(23).ToString();
                    bedg.Minqty = dr.GetValue(24).ToString();
                    bedg.Units = dr.GetValue(25).ToString();
                    bedg.Tstrength = dr.GetValue(26).ToString();
                    //,bedg .Netcost ,bedg .DiscPers ,bedg .DiscAmtt ,bedg .TransPers
                    bedg.AgsSubNetTot = dr.GetValue(27).ToString();
                    bedg.ClaimAmount = dr.GetValue(28).ToString();
                    string[] strDg = new string[] { bedg.SlNo, bedg.PrType, bedg.ItemName, bedg.BatchNo, bedg.ExpDte, bedg.Nounit, bedg.TotUnit, bedg.FreeQty, bedg.NetQty, bedg.Mrp, bedg.DiscPers, bedg.Discamt, bedg.BasicRate, bedg.VatPers, bedg.VatAmt, bedg.TransPers, bedg.Netcost, bedg.SellingPers, bedg.SellingMargin, bedg.SellingAmt, bedg.DummyRate, bedg.MrpValue, bedg.WpValue, bedg.Maxqty, bedg.Minqty, bedg.Units, bedg.Tstrength,bedg.AgsSubNetTot ,bedg.ClaimAmount };
                    dgvPurchase.Rows.Add(strDg);
                }
                dr.Close();
                con.Close();
            }
            catch
            {

            }
        }

Combobox Styles in C#

 cbxID.DropDownStyle = ComboBoxStyle.Simple;
            cbxSupName.DropDownStyle = ComboBoxStyle.DropDown;
            cbxBatchNo.DropDownStyle = ComboBoxStyle.Simple;

how can i Load items in Combobox or textbox in C#.NET

private void UserLoad()
        {
            string str = "Select username from T_CurUserPass";
            con = new OleDbConnection(dbCon());
            OleDbCommand cmd = new OleDbCommand(str, con);
            con.Open();
            OleDbDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                txtEditby.Text = dr.GetValue(0).ToString();
            }
            dr.Close();
            con.Close();
        }

Default DB Path Connections

  private string dbCon()
        {
            StreamReader sr = File.OpenText("dbCon.txt");
            string conread = sr.ReadLine();
            return conread;
        }

3 tire



3 - tire code for Save

variable Declarations

  ClsBEPurDetails be = new ClsBEPurDetails();
                                clsBEPurEntryStockUpdate beStock = new clsBEPurEntryStockUpdate();
                                clsDAPurEntry da = new clsDAPurEntry();

                                rc = dgvPurchase.Rows.Count - 1;
                                be.PurNo = cbxID.Text;
                                be.SupName = cbxSupName.Text;
                                for (int i = 0; i < rc; i++)
                                {
                                    be.PurNo = cbxID.Text;
                                    be.SlNo = dgvPurchase[0, i].Value.ToString();
                                    be.PrType = dgvPurchase[1, i].Value.ToString();
                                    be.ItemName = dgvPurchase[2, i].Value.ToString();
                                    be.BatchNo = dgvPurchase[3, i].Value.ToString();
                                    be.ExpDte = dgvPurchase[4, i].Value.ToString();
                                    be.Nounit = dgvPurchase[5, i].Value.ToString();
                                    be.TotUnit = dgvPurchase[6, i].Value.ToString();
                                    be.FreeQty = dgvPurchase[7, i].Value.ToString();
                                    be.NetQty = dgvPurchase[8, i].Value.ToString();
                                    be.Mrp = dgvPurchase[9, i].Value.ToString();
                                    be.DiscPers = dgvPurchase[10, i].Value.ToString();
                                    be.Discamt = dgvPurchase[11, i].Value.ToString();
                                    be.BasicRate = dgvPurchase[12, i].Value.ToString();
                                    be.VatPers = dgvPurchase[13, i].Value.ToString();
                                    be.VatAmt = dgvPurchase[14, i].Value.ToString();
                                    be.TransPers = dgvPurchase[15, i].Value.ToString();
                                    be.Netcost = dgvPurchase[16, i].Value.ToString();
                                    be.SellingPers = dgvPurchase[17, i].Value.ToString();
                                    be.SellingMargin = dgvPurchase[18, i].Value.ToString();
                                    be.SellingAmt = dgvPurchase[19, i].Value.ToString();
                                    be.DummyRate = dgvPurchase[20, i].Value.ToString();
                                    be.MrpValue = dgvPurchase[21, i].Value.ToString();
                                    be.WpValue = dgvPurchase[22, i].Value.ToString();
                                    be.Maxqty = dgvPurchase[23, i].Value.ToString();
                                    be.Minqty = dgvPurchase[24, i].Value.ToString();
                                    be.Units = dgvPurchase[25, i].Value.ToString();
                                    be.Tstrength = dgvPurchase[26, i].Value.ToString();
                                    be.AgsSubNetTot = dgvPurchase[27, i].Value.ToString();
                                    be.ClaimAmount = dgvPurchase[28, i].Value.ToString();

BAL CODE:

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

namespace BusinessEntities
{
    public class ClsBEPurDetails
    {
        private string _purNo;
        private string _supName;
        private string _SlNo;       
        private string _prType;      
        private string _itemName;
        private string _batchNo;       
        private string _expDte;
        private string _nounit;
        private string _totUnit;
        private string _freeQty;
        private string _netQty;
        private string _mrp;
        private string _discPers;
        private string _discamt;     
        private string _basicRate;    
        private string _VatPers;      
        private string _vatAmt;
        private string _TransPers;
        private string _netcost;       
        private string _sellingPers;       
        private string _sellingMargin;
        private string _sellingAmt;       
        private string _dummyRate;
        private string _mrpValue;
        private string _wpValue;       
        private string _Tstrength;       
        private string _Units;       
        private string _maxqty;        
        private string _minqty;
        private string _entryDate;
        private string _bV;
        private string _agsSubNetTot;
        private string _claimAmount;

        public string ClaimAmount
        {
            get { return _claimAmount; }
            set { _claimAmount = value; }
        }

        public string AgsSubNetTot
        {
            get { return _agsSubNetTot; }
            set { _agsSubNetTot = value; }
        }

        public string BV
        {
            get { return _bV; }
            set { _bV = value; }
        }

       

        public string PurNo
        {
            get { return _purNo; }
            set { _purNo = value; }
        }
        public string SupName
        {
            get { return _supName; }
            set { _supName = value; }
        }
        public string SlNo
        {
            get { return _SlNo; }
            set { _SlNo = value; }
        }
        public string PrType
        {
            get { return _prType; }
            set { _prType = value; }
        }
        public string ItemName
        {
            get { return _itemName; }
            set { _itemName = value; }
        }
        public string BatchNo
        {
            get { return _batchNo; }
            set { _batchNo = value; }
        }
        public string ExpDte
        {
            get { return _expDte; }
            set { _expDte = value; }
        }
        public string Nounit
        {
            get { return _nounit; }
            set { _nounit = value; }
        }
        public string TotUnit
        {
            get { return _totUnit; }
            set { _totUnit = value; }
        }
        public string FreeQty
        {
            get { return _freeQty; }
            set { _freeQty = value; }
        }
        public string NetQty
        {
            get { return _netQty; }
            set { _netQty = value; }
        }
        public string Mrp
        {
            get { return _mrp; }
            set { _mrp = value; }
        }

        public string DiscPers
        {
            get { return _discPers; }
            set { _discPers = value; }
        }
        public string Discamt
        {
            get { return _discamt; }
            set { _discamt = value; }
        }
        public string BasicRate
        {
            get { return _basicRate; }
            set { _basicRate = value; }
        }



        public string VatPers
        {
            get { return _VatPers; }
            set { _VatPers = value; }
        }
        public string VatAmt
        {
            get { return _vatAmt; }
            set { _vatAmt = value; }
        }
        public string TransPers
        {
            get { return _TransPers; }
            set { _TransPers = value; }
        }
        public string Netcost
        {
            get { return _netcost; }
            set { _netcost = value; }
        }
        public string SellingPers
        {
            get { return _sellingPers; }
            set { _sellingPers = value; }
        }
        public string SellingMargin
        {
            get { return _sellingMargin; }
            set { _sellingMargin = value; }
        }
        public string SellingAmt
        {
            get { return _sellingAmt; }
            set { _sellingAmt = value; }
        }
        public string DummyRate
        {
            get { return _dummyRate; }
            set { _dummyRate = value; }
        }
        public string MrpValue
        {
            get { return _mrpValue; }
            set { _mrpValue = value; }
        }
        public string WpValue
        {
            get { return _wpValue; }
            set { _wpValue = value; }
        }
        public string Tstrength
        {
            get { return _Tstrength; }
            set { _Tstrength = value; }
        }
        public string Units
        {
            get { return _Units; }
            set { _Units = value; }
        }
        public string Maxqty
        {
            get { return _maxqty; }
            set { _maxqty = value; }
        }
        public string Minqty
        {
            get { return _minqty; }
            set { _minqty = value; }
        }
        public string EntryDate
        {
            get { return _entryDate; }
            set { _entryDate = value; }
        }

    }
}

DAL : CODE   

   public void DAPurDatagridIntoDB(ClsBEPurDetails be)
    {
        string str = "Insert into T_PurDetails(ID,IDs,SupName,SlNo,Mname,ItemName,BatchNo,ExpDate,ItemsPbox,TotalBox,FreeQty,NetQty,MRP,DiscPers,DiscAmt,Basicrate,VatPers,VatAmt,TransPers,Netcost,SellPrice,SellingMargin,SellingAmt,DummyRate,MRPValue,WPValue,MaxQty,MinQty,Units,Strength,AgsSubNet,Claim)values('" + be.PurNo + "','" + be.PurNo + "','" + be.SupName + "','" + be.SlNo + "','" + be.PrType + "','" + be.ItemName + "','" + be.BatchNo + "','" + be.ExpDte + "','" + be.Nounit + "','" + be.TotUnit + "','" + be.FreeQty + "','" + be.NetQty + "','" + be.Mrp + "','" + be.DiscPers + "','" + be.Discamt + "','" + be.BasicRate + "','" + be.VatPers + "','" + be.VatAmt + "','" + be.TransPers + "','" + be.Netcost + "','" + be.SellingPers + "','" + be.SellingMargin + "','" + be.SellingAmt + "','" + be.DummyRate + "','" + be.MrpValue + "','" + be.WpValue + "','" + be.Maxqty + "','" + be.Minqty + "','" + be.Units + "','" + be.Tstrength + "','"+be.AgsSubNetTot +"','"+be.ClaimAmount+"')";
         con = new OleDbConnection(dbCon());
            OleDbCommand cmd = new OleDbCommand(str, con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

// save 
                                        da.DAPurDatagridIntoDB(be);//Purchase item insert

Why 3-Tier Architecture?

Why 3-Tier Architecture?

Still I can remember that, the first organization in my career was dealing with one small Point of Sales (POS) project. It was a Windows application and there was no layered architecture. We developers started to write all code in the Windows Forms Application. The problem started after a few days. How? When our manager announced that we need to develop one web version of the same product. Again we started to develop web pages from scratch and started to write all code. A total mess.

So, this is the problem and the solution is tierd architecture. If we separate our code by layers then changes in one layer will not affect another very much. Tomorrow if the business demands, we can change the UI very quickly by using existing code.

Difference between tier and layer

It is a confusing question for beginners. A few think that both are the same. But they are not the same. Tier represents multiple hardware boxes. In other words the components are physically separated into multiple machines. But in the case of layers all components are in the same system.

What are the Layers?

Theoretically it is N-tier architecture. So, we can create as many layers as possible but basically people classify code in three categories and put them in three layers. So, for this article we will consider N-tier architecture as 3-tier architecture and try to implement one sample application.

Let's explain each and every layer first.

Presentation Layer/ UI Layer

This is the top-most layer of the application where the user performs their activity. Let's take the example of any application where the user needs to fill up a form. This form is nothing but the Presentation Layer. In Windows applications Windows Forms are the Presentation Layer and in web applications the web form belongs to the Presentation Layer. Basically the user's input validation and rule processing is done in this layer.

Business Layer

This is on top of the Presentation Layer. As the name suggests, most of the business operations are performed here. For example, 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

On top of the Business Logic Layer is the Data Access Layer. It contains methods that help the business layer to connect with the database and perform CRUD operations. Generally all database related code and stuff belongs to the Data Access Layer. Sometimes people use a platform-independent Data Access Layer to fetch data from various database vendors.

Let's Implement

Before starting with an example, one more question needs to be clarified. How will we pass data from one layer to another layer? In other words, in which form is the data passed?
There are many solutions for this problem. For our example we will pass data using function parameters. In this example we will implement one small Windows application to fetch data from the database using 3-tier architecture. In this example we will read data from a single "Person" Table.

Code for Data Access Layer

Let's start from the Data Access Layer; we will create a function to read data from the database. Have a look at the following code.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace WindowsFormsApplication1.DAL
{
    public class PersonDAL
    {
        public string ConString = "Data Source=SOURAV-PC\\SQL_INSTANCE;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 Person",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 Person where ID= "+ Id +"", con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }

    }
}
We have created two overloadeded functions to read data. One function will not take any arguments and other functions will fetch data using ID.

Create Business Logic Layer

We will now create a Business Logic Layer to communicate with both the Presentation Layer and Data Access Layer. Here is our code for the Business 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 the user interacts with the system. We will create simple windows as in the following:

Layer1.jpg

The form contains one DataGrid, one TextBox and one Button. In the load event of the form we will pull all data and it will show in the DataGrid. There is another operation, where can the user fetch a specific person by providing the person's ID. Have a look at the following code.
 
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");
            }
        }
    }
}

So, this is the entire project structure:

Layer2.jpg

Here is sample output in the form load event.

Layer3.jpg

If we want to search for a specific person then we need to provide an ID.

Layer4.jpg

Table Structure

Here is our table structure. It contains the three fields ID, name and surname. 

Table Name: Person

Layer5.jpg

Conclusion

In this article we have seen how to implement simple 3-tier architecture in .NET. Hope you have understood the concept. In a future article we will concentrate more on 3-tier architecture.