how to write a 3layers winform applications in c#?

Farshad Valizade 481 Reputation points
2023-01-25T15:43:48.5766667+00:00

hi every body

i am noob in c# and programming and i really care to code right and learn c# programming very correctly. so at first I want to write a 3 layers win form applications that read and write data into a table in sql server.

for this project I made 2 class and 1 form.

class DocumentDAL fro Data Layer

class DocumentBLL for Business Layer

winform for VIEW.

my codes:

DocumentDAL :


internal class DocumentDAL
    {
        private SqlConnection conn = new SqlConnection("Server=SQLSERVER.1;Integrated Security=SSPI;Persist Security Info=False;User ID=kiansaze;Initial Catalog=Karjoo;Data Source=DESKTOP-UKJISPV");
        internal int DocID;
        internal int DocRev;
        internal string DocTitle;

        public DataTable Select()
        { 
            string sqlcommand = "select * from Document";
            SqlDataAdapter da = new SqlDataAdapter(sqlcommand, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }

        public int Add()
        {
            string query = "insert into Document values(@doctitle,@docrev)";
            SqlCommand cmd = new SqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@doctitle", this.DocTitle);
            cmd.Parameters.AddWithValue("@docrev", this.DocRev);
            int result = cmd.ExecuteNonQuery();
            return result;
        }
        public int Update()
        {
            string query = "update Document set doctitle = @doctitle,docrev=@docrev where docid = @docid";
            SqlCommand cmd = new SqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@docid", this.DocID);
            cmd.Parameters.AddWithValue("@doctitle", this.DocTitle);
            cmd.Parameters.AddWithValue("@docrev", this.DocRev);
            int result = cmd.ExecuteNonQuery();
            return result;
        }
    }

DocumentBLL :

internal class DocumentBLL
    {
        private DocumentDAL _docDal ;

        public  int DocID { get; set; }
        public int DocRev { get; set; }
        public string DocTitle { get; set; }

        public DataTable Select()
        {
            _docDal = new();
            return _docDal.Select();
        }

        public bool Add()
        {
            _docDal = new();
            if (_docDal.Add() > 0)
                return true;
            else
                return false;

        }
        public bool Update()
        {
            _docDal = new();
            if (_docDal.Update() > 0)
                return true;
            else
                return false;
        }


    }

Form:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DocumentBLL documentBLL = new DocumentBLL();
            documentBLL.DocTitle = txtDocTitle.Text;
            documentBLL.DocRev = int.Parse(txtDocRev.Text);
            if (documentBLL.Add())
            {
                MessageBox.Show("Add Success");
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            DocumentBLL documentBLL = new DocumentBLL();
            documentBLL.DocID = int.Parse(dataGridView1.SelectedRows[0].Cells["DocID"].Value.ToString());
            documentBLL.DocTitle = txtDocTitle.Text;
            documentBLL.DocRev = int.Parse(txtDocRev.Text);
            if (documentBLL.Update())
            {
                MessageBox.Show("Update Success");
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            DocumentBLL documentBLL = new DocumentBLL();
            dataGridView1.DataSource = documentBLL.Select();
        }
    }

I do this but didn't know is it true coding or not?

Are DocumentDAL and DocumentBLL class Right?

Please check my code and tell me is this way of programming 3layers rights?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,010 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Hui Liu-MSFT 48,571 Reputation points Microsoft Vendor
    2023-01-27T08:21:56.8933333+00:00

    Hi,@Farshad Valizade . Welcome Microsoft Q&A.

    For the three layers winform project, you could try the following example.

    Form1.cs:

    using WinFormsApp1.BLL;
    using WinFormsApp1.DAL;
    namespace WinFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
              
            }
      
            private void btnAdd_Click(object sender, EventArgs e)
            {
                DocumentHandler documentH = new DocumentHandler();
                if (documentH.InsertDocument(new DAL.Document() { DocRev = int.Parse(txtDocRev.Text), DocTitle = txtDocTitle.Text, DocID= int.Parse(txtDocId.Text) }))
                {
                    MessageBox.Show("Add Success");
                    dataGridView2.DataSource = documentH.GetDocuments();
                }
                
            }
            private void dataGridView2_SelectionChanged(object sender, EventArgs e)
            {
                if (dataGridView2.SelectedRows.Count > 0) // make sure user select at least 1 row 
                {
                    string Id = dataGridView2.SelectedRows[0].Cells[0].Value + string.Empty;
                    string Rev = dataGridView2.SelectedRows[0].Cells[1].Value + string.Empty;
                    string Title = dataGridView2.SelectedRows[0].Cells[2].Value + string.Empty;
                    txtDocId.Text = Id;
                    txtDocTitle.Text = Title;
                    txtDocRev.Text = Rev;
                }
            }
            private void btnEdit_Click(object sender, EventArgs e)
            {
                DocumentHandler documentH = new DocumentHandler();
                if (documentH.UpdateDocument(new DAL.Document() { DocRev = int.Parse(txtDocRev.Text), DocTitle = txtDocTitle.Text,
                    DocID = int.Parse(txtDocId.Text)
                }))
                {
                    MessageBox.Show("Add Success");
                    dataGridView2.DataSource = documentH.GetDocuments();
                }
              
            }
            private void btnSelect_Click(object sender, EventArgs e)
            {
                try
                {
                    DocumentHandler d = new DocumentHandler();
                    this.dataGridView2.DataSource = d.GetDocuments(Convert.ToInt16(this.txtID.Text));
                }
                catch
                {
                    MessageBox.Show("Error Occurred");
                }
            }
          
            private void Form1_Load(object sender, EventArgs e)
            {
                try
                {
                    
                   
                    DocumentHandler d = new DocumentHandler();
                    this.dataGridView2.DataSource = d.GetDocuments();
                }
                catch
                {
                    MessageBox.Show("Error Occurred");
                }
            }
        
        }
    }
    

    BLL:

    using System.Data;
    using WinFormsApp1.DAL;
    using Document = WinFormsApp1.DAL.Document;
    namespace WinFormsApp1.BLL
    {
       
        public class DocumentHandler
        {
            public DataTable GetDocuments()
            {
                try
                {
                    DocumentDAL objdal = new DocumentDAL();
                    return objdal.Read();
                }
                catch
                {
                    throw;
                }
            }
            public DataTable GetDocuments(Int16 ID)
            {
                try
                {
                    DocumentDAL objdal = new DocumentDAL();
                    return objdal.Read(ID);
                }
                catch
                {
                    throw;
                }
            }
            public bool InsertDocument(Document document)
            {
                if (DocumentDAL.Validate(document))
                {
                    DocumentDAL.Add(document);
                    return true;
                }
                return false;
            }
            public bool UpdateDocument(Document document)
            {
                if (DocumentDAL.Validate(document))
                {
                    DocumentDAL.Update(document);
                    return true;
                }
                return false;
            }
        }
       
    }
    

    DAL:

    
    using System.Data;
    using System.Data.SqlClient;
    
    namespace WinFormsApp1.DAL
    {
       
        public  class Document
        {
            public int DocID { get; set; }
            public int DocRev { get; set; }
            public string DocTitle { get; set; }
        }
        internal class DocumentDAL
        {
            public static string ConString = "constr";
            static SqlConnection conn = new SqlConnection(ConString);
           
            DataTable dt = new DataTable();
            public DataTable Read()
            {
    
                if (ConnectionState.Closed == conn.State)
                    conn.Open();
                SqlCommand cmd = new SqlCommand("select * from [dbo].[Document]", conn);
              
                try
                {
                    SqlDataReader rd = cmd.ExecuteReader();
                    dt.Load(rd);
                    return dt;
                }
                catch
                {
                    throw;
                }
            }
            public DataTable Read(Int16 Id)
            {
    
                if (ConnectionState.Closed == conn.State)
                    conn.Open();
                SqlCommand cmd = new SqlCommand("select * from Person where ID= " + Id + "", conn);
                try
                {
                    SqlDataReader rd = cmd.ExecuteReader();
                    dt.Load(rd);
                    return dt;
                }
                catch
                {
                    throw;
                }
            }
            public DataTable Select()
            {
    
                if (ConnectionState.Closed == conn.State)
                    conn.Open();
                string sqlcommand = "select * from [dbo].[Document]";
                SqlDataAdapter da = new SqlDataAdapter(sqlcommand, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
    
            public static void  Add(Document d)
            {
                if (ConnectionState.Closed == conn.State)
                    conn.Open();
                string query = "insert into [dbo].[Document]([DocID],[DocTitle],[DocRev]) values(@docid, @doctitle,@docrev)";
                SqlCommand cmd = new SqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@docid", d.DocID);
                cmd.Parameters.AddWithValue("@doctitle", d.DocTitle);
                cmd.Parameters.AddWithValue("@docrev", d.DocRev);
                cmd.ExecuteNonQuery();
               
            }
            public static void Update(Document d)
            {
                if (ConnectionState.Closed == conn.State)
                    conn.Open();
                string query = "update [dbo].[Document] set DocTitle = @doctitle,DocRev=@docrev where DocID = @docid";
                SqlCommand cmd = new SqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@docid", d.DocID);
                cmd.Parameters.AddWithValue("@doctitle", d.DocTitle);
                cmd.Parameters.AddWithValue("@docrev", d.DocRev);
                cmd.ExecuteNonQuery();
               
            }
            internal static bool Validate(Document d)
            {
                return true;
                // some validations before insert 
            }
        }
    }
    
    

    The result:

    21


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

  2. Bruce (SqlWork.com) 66,706 Reputation points
    2023-01-25T16:54:09.7333333+00:00

    proper laying would make each layer a project with unit tests.

    also not keen about the DAL & BLL layers returning datatables rather than POCO objects or records.

    1 person found this answer helpful.
    0 comments No comments

  3. Bruce (SqlWork.com) 66,706 Reputation points
    2023-01-25T17:02:17.7933333+00:00

    duplicate post

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.