C# DataGridView - Simple Master Detail

June 20, 2017 Oclemy C# DataGridView, C# Form 1 minute, 25 seconds

DataGridView belongs to System.Windows.Forms namespace.

Needless to say, displaying data in tabular or grid-like format is a task we do commonly. And datagridview is a winform component that provides us with a complete solution to make applications that work with tabular data.

Today we want to see a basic master detail example with DataGridView.Wherebey we have two forms :

  • Master Form : - Contains our DataGridView with tabular data.
  • DetailForm : - Contains simple TextBoxes to display data passed from Master Form.

Our Master Form

  • Contains list of data.
  • Opens new Form when cellcontents are clicked.
using System.Windows.Forms;

namespace DGView_M_Detail
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //SETUP DG COLUMNS
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Name";
            dataGridView1.Columns[1].Name = "Propellant";
            dataGridView1.Columns[2].Name = "Description";

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            FillDView();

        }

        private void FillDView()
        {
            //add data
            string[] row = { "Spizter", "Anti-Matter", "This was one of the..." };
            dataGridView1.Rows.Add(row);

            row = new[] { "Casini", "Chemical", "Casini was...." };
            dataGridView1.Rows.Add(row);

            row = new[] { "Opportunity", "Solar", "This revolutionized..." };
            dataGridView1.Rows.Add(row);
            row = new[] { "Hubble", "Laser Beam", "One of the most modern..." };
            dataGridView1.Rows.Add(row);
            row = new[] { "Pioneer", "Nuclear", "Among the first..." };
            dataGridView1.Rows.Add(row);
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //GET DATA
             string name = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
             string prop = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
             string desc = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();

            //OPEN DETAIL FORM
             new DetailForm(name,prop,desc).Show();
        }
    }
}

Our Detail Form

  • Contains TextBoces to hold data received from Master Form.
using System.Windows.Forms;

namespace DGView_M_Detail
{
    public partial class DetailForm : Form
    {
        public DetailForm(string name, string prop, string desc)
        {
            InitializeComponent();

            nameTxt.Text = name;
            propTxt.Text = prop;
            descTxt.Text = desc;

        }
    }
}

Best Regards.

Comments