Working with DataGridView - potatoscript/csharp GitHub Wiki

πŸ₯” Working with DataGridView in C# πŸ₯”


🎯 What is a DataGridView?

Imagine you have a potato restaurant menu πŸ₯”πŸ“œ with a list of potatoes, their prices, and how much stock is available. You need a way to display and manage that data in a table.

A DataGridView in C# is like a fancy potato menu that can show and organize data, and even let users add, edit, and delete rows of data in it.

It’s like your potato display board where customers can see the available potatoes, prices, and stock levels!


πŸ₯” Why Use DataGridView?

A DataGridView is useful because:

  • You can display large amounts of data in an organized table.
  • Users can edit, add, or delete rows.
  • It’s easy to customize (like adding potato pictures, changing row colors, etc.).

🎨 Adding a DataGridView to Your Form

Let’s get started with adding a DataGridView to your potato restaurant form!


🎁 Step 1: Add a DataGridView to Your Form

  • Open your Form.
  • Drag and drop a DataGridView from the Toolbox onto the form.
  • Resize it to fit the screen.
  • Set the Name property of the DataGridView to dataGridViewPotatoes.

🎁 Step 2: Set Up Columns in DataGridView

Columns represent the different types of information you want to show, like potato type, price, and stock.

You can add columns either manually or automatically.


πŸ₯” Manual Column Setup:

  1. Select the DataGridView on your form.
  2. Go to the Properties window and click on the Columns property.
  3. Add the following columns:
    • Column 1: Name – Potato Type
    • Column 2: Name – Price
    • Column 3: Name – Stock

πŸ₯” Automatic Column Setup in Code:

If you prefer to set columns in code, here’s how:

private void Form1_Load(object sender, EventArgs e)
{
    // Add columns manually in code
    dataGridViewPotatoes.Columns.Add("potatoType", "Potato Type");
    dataGridViewPotatoes.Columns.Add("price", "Price");
    dataGridViewPotatoes.Columns.Add("stock", "Stock");
}

🎁 Step 3: Add Data to the DataGridView

You can add data manually or programmatically, like when potatoes are added to your menu.

private void AddPotato()
{
    string[] potatoRow = new string[] { "Mashed Potato", "5.00", "20" };
    dataGridViewPotatoes.Rows.Add(potatoRow);
}

πŸ§‘β€πŸ’» Complete Example to Add Data:

private void btnAddPotato_Click(object sender, EventArgs e)
{
    string potatoType = txtPotatoType.Text; // Get potato type from TextBox
    string price = txtPrice.Text;           // Get price from TextBox
    string stock = txtStock.Text;           // Get stock from TextBox

    // Add potato data to DataGridView
    string[] row = new string[] { potatoType, price, stock };
    dataGridViewPotatoes.Rows.Add(row);
}

πŸ₯” Editing Data in DataGridView

You can allow users to edit data in the DataGridView directly, like changing the price of a potato.

When users click on a cell, they can type a new value, and the table will update automatically.


πŸ§‘β€πŸ’» Enabling Editing:

By default, the DataGridView allows users to edit values. If you want to make sure it's enabled, you can do this:

dataGridViewPotatoes.ReadOnly = false; // Allow editing

🎁 Step 1: Edit Data in DataGridView

If you want to capture the new edited values, you can handle the CellValueChanged event.

private void dataGridViewPotatoes_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show("Potato information updated!");
}

πŸ§‘β€πŸ’» Complete Example for Editing Data:

private void dataGridViewPotatoes_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    string updatedPotatoType = dataGridViewPotatoes.Rows[e.RowIndex].Cells[0].Value.ToString();
    string updatedPrice = dataGridViewPotatoes.Rows[e.RowIndex].Cells[1].Value.ToString();
    string updatedStock = dataGridViewPotatoes.Rows[e.RowIndex].Cells[2].Value.ToString();

    MessageBox.Show($"Updated: {updatedPotatoType}, Price: {updatedPrice}, Stock: {updatedStock}");
}

πŸ₯” Deleting Data in DataGridView

Sometimes you need to remove a row of data, like when a potato type is no longer available.

🎁 Step 1: Delete a Row from DataGridView

You can delete a row by clicking a button, like a "Delete" button for each row.

private void btnDeletePotato_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridViewPotatoes.SelectedRows)
    {
        dataGridViewPotatoes.Rows.Remove(row);
    }
}

πŸ§‘β€πŸ’» Complete Example for Deleting Rows:

private void btnDeletePotato_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridViewPotatoes.SelectedRows)
    {
        dataGridViewPotatoes.Rows.Remove(row);
    }
}

🎨 Formatting the DataGridView

You can style your DataGridView like a fancy potato restaurant menu πŸ₯”βœ¨.

Here are some formatting tips:

  1. Change the row color when a potato is out of stock.
  2. Add borders to make the table look neat.

🎁 Step 1: Change Row Color Based on Stock

private void dataGridViewPotatoes_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 2) // Check if it's the "Stock" column
    {
        if (e.Value.ToString() == "0") // If out of stock
        {
            e.CellStyle.BackColor = Color.Red; // Set cell color to red
        }
        else
        {
            e.CellStyle.BackColor = Color.Green; // Set cell color to green
        }
    }
}

πŸ§‘β€πŸ’» Complete Example for Row Coloring:

private void dataGridViewPotatoes_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 2) // Stock column
    {
        if (e.Value.ToString() == "0")
        {
            e.CellStyle.BackColor = Color.Red; // Out of stock -> Red
        }
        else
        {
            e.CellStyle.BackColor = Color.Green; // In stock -> Green
        }
    }
}

πŸ₯” Sorting and Filtering Data

You can also sort and filter the potato menu to make it easier for customers to find what they want.


🎁 Step 1: Enable Sorting

Sorting allows users to sort the potato list by name, price, or stock.

dataGridViewPotatoes.Sort(dataGridViewPotatoes.Columns["price"], ListSortDirection.Ascending);

🎁 Step 2: Enable Filtering

You can filter the data based on specific criteria, like showing only potatoes in stock.

private void FilterPotatoes()
{
    DataView view = new DataView(potatoDataTable);
    view.RowFilter = "stock > 0"; // Filter out potatoes that are out of stock
    dataGridViewPotatoes.DataSource = view;
}

🎯 Putting It All Together – Potato Menu App

You can use the DataGridView to create an interactive Potato Menu App where customers can see, add, edit, and delete potato types, prices, and stock.


🎁 Final Potato Menu App Code:

using System;
using System.Windows.Forms;
using System.Data;

namespace PotatoMenuApp
{
    public partial class Form1 : Form
    {
        private DataTable potatoDataTable;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Create and setup DataTable
            potatoDataTable = new DataTable();
            potatoDataTable.Columns.Add("Potato Type");
            potatoDataTable.Columns.Add("Price");
            potatoDataTable.Columns.Add("Stock");

            dataGridViewPotatoes.DataSource = potatoDataTable;
        }

        private void btnAddPotato_Click(object sender, EventArgs e)
        {
            // Add potato to the menu
            string potatoType = txtPotatoType.Text;
            string price = txtPrice.Text;
            string stock = txtStock.Text;

            potatoDataTable.Rows.Add(potatoType, price, stock);
        }

        private void btnDeletePotato_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridViewPotatoes.SelectedRows)
            {
                dataGridViewPotatoes.Rows.Remove(row);
            }
        }
    }
}

πŸ₯” Summary of Working with DataGridView

  • DataGridView is used to display and manage data in a tabular format.
  • You can add, edit, delete, and format data.
  • Events like CellValueChanged help you capture changes.
  • You can sort and filter data to make it easier to navigate.