Advanced 15 min read Control #5

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

  1. Drag a DataGridView onto your form.
  2. Rename it (e.g., dgvStudents).
  3. Set Dock to Fill to fill the form.
  4. Bind data using the DataSource property.
  5. 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.

  1. Create a DataGridView with columns: ProductID, Name, Price, Category.
  2. Add 5-10 sample products manually.
  3. Add a TextBox for searching/filtering products.
  4. Add a Button that shows details of the selected product.
  5. 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.