DataGridView Control
The DataGridView is a powerful control for displaying and editing tabular data. It's like a spreadsheet in your Windows Forms application.
What is a DataGridView?
The DataGridView is the most powerful data display control in Windows Forms. It shows data in rows and columns, supports sorting, filtering, editing, and data binding to databases.
Common uses: Displaying database tables, Excel-like data views, order lists, customer databases.
How to Use
- Drag a DataGridView onto your form.
- Rename it (e.g.,
dgvStudents). - Set Dock to Fill to fill the form.
- Bind data using the DataSource property.
- Customize columns in the designer or in code.
Code Example
// 1. Bind data from a DataTable
private void LoadData()
{
using (var connection = new SqlConnection(connectionString))
{
var adapter = new SqlDataAdapter("SELECT * FROM Students", connection);
var table = new DataTable();
adapter.Fill(table);
dgvStudents.DataSource = table;
}
}
// 2. Get selected row data
private void dgvStudents_SelectionChanged(object sender, EventArgs e)
{
if (dgvStudents.CurrentRow == null) return;
string name = dgvStudents.CurrentRow.Cells["FirstName"].Value?.ToString();
MessageBox.Show($"Selected: {name}");
}
// 3. Customize columns
private void SetupGrid()
{
dgvStudents.Columns["StudentId"].Visible = false;
dgvStudents.Columns["FirstName"].Width = 150;
dgvStudents.Columns["LastName"].Width = 150;
dgvStudents.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
Exercise
Task: Create a simple product catalog with DataGridView.
- Create a DataGridView with columns: ProductID, Name, Price, Category.
- Add 5-10 sample products manually.
- Add a TextBox for searching/filtering products.
- Add a Button that shows details of the selected product.
- Add a Button that adds a new row.
Key Takeaway
DataGridView is your go-to control for tabular data. It supports sorting, filtering, editing, and database binding.