C# Windows Forms - DataGridView - Fill From HashSet


So we want to create a dataGridView with a HashSet of data. Then we handle the ItemSelection events for our datagridview thus showing the selected row in a messagebox.

Let's go.

1. Create Empty Project

  1. Open up Visual Studio and proceed over to File --> New Project

  2. A new dialog popus up like this:

Create Project

  1. Give our empty project a name and click OK. An empty project will get generated for us.

2. Make project a Windows Project

Just right click on your project choose properties and set output type to Windows Application:

Choose Project Type

3.Program.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DataGridViewHashset
{
    static class Program
    {
        private static DataGridView myDataGridView;
        private static bool executedFirstTime = true;
        public static void Main()
        {
            setupDataGridView();
            createForm();
        }
        /*
         * Create a Form, Set its properties and run the application.
         */
        private static void createForm()
        {
            Form myForm = new Form
            {
                Text = "C# WinForms : DataGridView - Fill From HashSet - Camposha.info",
                ClientSize = new Size(564, 520),
                BackColor = Color.DodgerBlue
            };

            myForm.Controls.Add(myDataGridView);
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }
        /*
         * Setup DataGridView. Intantiate it, set its properties and attach an event listener
         */
        private static void setupDataGridView()
        {
            myDataGridView = new DataGridView
            {
                Location = new Point(30, 70),
                Size = new Size(500, 400),
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                ColumnCount = 2
            };
            myDataGridView.Columns[0].Name = "NAME";
            myDataGridView.Columns[1].Name = "CATEGORY";

            populateData();
            myDataGridView.SelectionChanged += myDataGridView_SelectionChanged;
        }

        /*
         * For this to work you must set DataGridView SelectionMode property to `DataGridViewSelectionMode.FullRowSelect`
         */
        static void myDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (executedFirstTime)
            {
                executedFirstTime = false;
                return;
            }
            try
            {
                int selectedIndex = myDataGridView.SelectedRows[0].Index;
                if (selectedIndex != -1)
                {
                    if (myDataGridView.SelectedRows[0].Cells[0].Value != null)
                    {
                        string name = myDataGridView.SelectedRows[0].Cells[0].Value.ToString();

                        MessageBox.Show(name);
                    }

                }
            }
            catch (ArgumentOutOfRangeException argumentOutOfRangeException)
            {
                MessageBox.Show(argumentOutOfRangeException.Message);
            }

        }
        /*
         * Generate data and bind to our datagridview
         */
        private static void populateData()
        {
            HashSet<string> nebulae = new HashSet<string>
            {
                "Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Elephant's Trunk", "Helix", "Rosette","Snake","Bernad 68",
                "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Cone", "Flame", "Witch Head", "Bumerang"
            };
            HashSet<string> nebularCategory = new HashSet<string>
            {
                "HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS",
                "DARK NEBULAR"
            };
            Random r = new Random();
            foreach (string nebular in nebulae)
            {
                myDataGridView.Rows.Add(nebular, nebularCategory.ToArray()[r.Next(0, 5)], (r.Next(9, 9999)).ToString());
            }
        }
    }
}

Best Regards,Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post