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:
- Select the DataGridView on your form.
- Go to the Properties window and click on the Columns property.
- Add the following columns:
- Column 1: Name β
Potato Type
- Column 2: Name β
Price
- Column 3: Name β
Stock
- Column 1: Name β
π₯ 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:
- Change the row color when a potato is out of stock.
- 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.