C# Programming - How to Create a Master-Detail Windows Forms


C# Programming - Creating a Master-Detail Windows Forms.

🎓 Master Visual Basic .NET and Access Database By Building the Point Of Sale System (POS).
ðŸ“ē Enroll Now: https://bit.ly/2WcbRhX

Visual Basic .Net Version: » https://goo.gl/Je25Vx

★✩★ Full HD Video ★✩★
Thank you so much for watching. I hope you enjoyed my videos. Please don't forget to like, comment, share and subscribe to my channel.

✩ Part 1 - Adding a Class to a Project.

✩ Part 2 Connecting to SQL Server Database and Displaying Data in DataGridView.

✩ Part 3 How to Open a Form from Another Form Using DataGridViewLinkColumn.

[Screenshot]

[Source Code]

Class - SqlConn:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace CSharp_MasterDetails
{
    static class SqlConn
    {
        public static string sql;
        public static SqlConnection con = new SqlConnection();
        public static DataSet ds;
        public static SqlCommand cmd;
        public static SqlDataAdapter da;
        public static BindingSource bs;

        public static string GetConnectionString()
        {
            string ConnectionString = @"Data Source = CodeAMinute\SQLEXPRESS;" +
                                       "Initial Catalog = Northwind;" +
                                       "Integrated Security = True;" +
                                       "MultipleActiveResultSets = True;";
            return ConnectionString;
        }

        public static string MyApp()
        {
            string AppTitle = "C# - Master Details (SQL Server) - Code A Minute.";
            return AppTitle;
        }

        public static void ConnectionState()
        {
            string msg = "Connection state: " + "The connection is ";
            string title = SqlConn.MyApp();
            MessageBoxButtons btn = MessageBoxButtons.OK;
            MessageBoxIcon ico = MessageBoxIcon.Information;

            MessageBox.Show(msg + con.State.ToString(), title, btn, ico);
        }

        public static void OpenCon()
        {
            con.Close();
            try
            {
                con.ConnectionString = SqlConn.GetConnectionString();
                con.Open();
            }              
            catch (Exception e)
            {
                MessageBox.Show("The system failed to establish a connection." +
                    Environment.NewLine + e);
            }
            finally
            {
                ConnectionState();
            }
        }
        public static void CloseCon()
        {
            con.Close();
            con.Dispose();
            ConnectionState();
        }

    }
}

Form - Form1 :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSharp_MasterDetails
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Text = SqlConn.MyApp();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SqlConn.sql = "SELECT * FROM dbo.Categories";
            SqlConn.OpenCon();
            SqlConn.cmd = new SqlCommand(SqlConn.sql, SqlConn.con);

            SqlConn.da = new SqlDataAdapter(SqlConn.cmd);
            SqlConn.ds = new DataSet();
            SqlConn.bs = new BindingSource();

            SqlConn.da.Fill(SqlConn.ds, "myCats");

            foreach(DataRow r in SqlConn.ds.Tables["myCats"].Rows)
            {
                ListBox1.Items.Add(r["CategoryName"].ToString());
            }

            ListBox1.ValueMember = "CategoryID";

            SqlConn.bs.DataSource = SqlConn.ds.Tables["myCats"];

            txtCatID.DataBindings.Add("Text", SqlConn.bs, "CategoryID");
            txtCatName.DataBindings.Add("Text", SqlConn.bs, "CategoryName");
            txtDesc.DataBindings.Add("Text", SqlConn.bs, "Description");

            PictureBox1.DataBindings.Add("Image", SqlConn.bs, "Picture", true);

            ListBox1.SelectedIndex = 0;

            var link = new DataGridViewLinkColumn();

            link.DisplayIndex = 0;
            link.DefaultCellStyle.NullValue = "Select";
            link.DefaultCellStyle.Alignment =
                DataGridViewContentAlignment.MiddleCenter;

            link.Width = 60;

            link.ActiveLinkColor = Color.White;
            link.LinkBehavior = LinkBehavior.HoverUnderline;
            link.LinkColor = Color.Crimson;
            link.TrackVisitedState = true;
            link.VisitedLinkColor = Color.YellowGreen;

            DataGridView1.Columns.Add(link);

            DataGridView1.AllowUserToAddRows = false;

            ShowProducts();

        }
     
        private void ShowProducts()
        {
            try
            {
                if (SqlConn.ds.Tables["myProducts"] != null)
                {
                    SqlConn.ds.Tables["myProducts"].Clear();
                }

                SqlConn.sql = "SELECT * ";
                SqlConn.sql += "FROM Products ";
                SqlConn.sql += "WHERE CategoryID = ";
                SqlConn.sql += "'" + txtCatID.Text + "'";

                SqlConn.cmd.CommandText = SqlConn.sql;
                SqlConn.da.SelectCommand = SqlConn.cmd;
                SqlConn.da.Fill(SqlConn.ds, "myProducts");

                DataGridView1.DataSource = SqlConn.ds.Tables["myProducts"];

                DataGridView1.Columns[0].DefaultCellStyle.Alignment =
                    DataGridViewContentAlignment.MiddleCenter;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.ToString(), "Error Handler - Code A Minute.");
            }      
            finally
            {
                SqlConn.da.Dispose();
                SqlConn.cmd.Dispose();
                SqlConn.con.Close();
            }
        }

        private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(SqlConn.bs != null)
            {
                SqlConn.bs.Position = ListBox1.SelectedIndex;
            }

            ShowProducts();

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(SqlConn.con.State != ConnectionState.Closed)
            {
                SqlConn.CloseCon();
            }
         
        }

        private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var dgv = DataGridView1;
            if(e.ColumnIndex == 10) // Link Column
            {
                int r = dgv.CurrentRow.Index;

                myPro.ProID = Convert.ToInt32(dgv[0, r].Value);
                myPro.ProName = Convert.ToString(dgv[1, r].Value);
                myPro.QtyPerUnit = Convert.ToString(dgv[4, r].Value);
                myPro.ProPrice = Convert.ToInt32(dgv[5, r].Value);
                myPro.UInStock = Convert.ToInt32(dgv[6, r].Value);
                myPro.RLevel = Convert.ToInt32(dgv[8, r].Value);

                myPro.IsDiscontinued = Convert.ToBoolean(dgv[9, r].Value);

                myPro.CatName = txtCatName.Text.ToString();

                var f = new ProductDetails();
                f.ShowDialog();
            }
        }
    }
}

Class - myPro :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSharp_MasterDetails
{
    static class myPro // Products
    {
        public static int ProID;
        public static string ProName;
        public static string QtyPerUnit;
        public static double ProPrice;
        public static int UInStock;
        public static int RLevel;
        public static bool IsDiscontinued;
        public static string CatName;
        public static void GetProInfo()
        {
            string pid = "Product ID: " + Convert.ToString(ProID);
            string pname = "Product Name: " + ProName;
            string cname = "Category Name: " + CatName;

            MessageBox.Show(pid + Environment.NewLine +
                pname + Environment.NewLine + cname, SqlConn.MyApp(),
                MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
    }
}

Form - ProductDetails :

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;

namespace CSharp_MasterDetails
{
    public partial class ProductDetails : Form
    {
        public ProductDetails()
        {
            InitializeComponent();
        }

        private void ProductDetails_Load(object sender, EventArgs e)
        {
            txtProID.Text = myPro.ProID.ToString();
            txtProName.Text = myPro.ProName.ToString();
            txtQtyPerUnit.Text = myPro.QtyPerUnit.ToString();
            txtPrice.Text = myPro.ProPrice.ToString("C3",
                System.Globalization.CultureInfo.CreateSpecificCulture("ja-JP"));

            txtUInStock.Text = myPro.UInStock.ToString();
            txtRLevel.Text = myPro.RLevel.ToString();

            if(myPro.IsDiscontinued)
            {
                chkDiscontinued.Checked = true;
            }
            else
            {
                chkDiscontinued.Checked = false;
            }

            txtCatName.Text = myPro.CatName.ToString();

            myPro.GetProInfo();

        }
    }
}

★✩★ Follow me on ★✩★

Twitter

Facebook

Google+

YouTube Channel

Thank you very much.
āļ‚āļ­āļšāļ„ุāļ“āļ„āļĢัāļš.

Comments

  1. virtual edge. Sales 101 also plenty of event organizers overlook this fact when the need for sponsors becomes urgent and overbearing and It's not uncommon for event organizers to develop a kind of tunnel vision as they get desperate in their quest to secure event sponsors. post event thank you email and thanks for coming message

    ReplyDelete
  2. If these keys don't work, you can use Windows Loader v2.2.2 to activate windows 7 ultimate 64 bit. You copy and paste the key as below image .Windows 7 Ultimate Code Key

    ReplyDelete
  3. How to download? · The first step is to open the internet browser that you're using after open it simply the first thing you have to do is go to .Grammarly Crack Version

    ReplyDelete

  4. Great blog! Keep sharing your content consistently.

    for more informartion click here!

    best python full stack training in hyderabad

    ReplyDelete

Post a Comment