Getting data from a WinForms DataGridView

Now, I know this is out-of-date tech these days, but there’s a lot of it about (indeed, I’m working on it right now), so this may be of some use.

It’s tempting when getting data from a DataGridView to get the data from the cells, like so:

if (dataGridView1.SelectedRows.Count == 0) return;
string employeeName = (string)dataGridView1.SelectedRows[0].Cells[4].Value;

However, it’s far better to work with the data that is bound to the grid instead, like so:

if (dataGridView1.SelectedRows.Count == 0) return;
CrmDataSet.EmployeeRow selectedEmployeeRow = (CrmDataSet.EmployeeRow)((DataRowView)dataGridView1.SelectedRows[0].DataBoundItem).Row;
string employeeName = selectedEmployeeRow.EmployeeName;

Now you get the benefit of refactoring tools like Resharper, and you don’t need to worry about future layout changes (like adding/removing/rearranging columns) from breaking your code.

In fact, I’ve written this up as a little extension method, since it’s fairly common.  Let me know what you think in the comments:

using System.Data;

namespace System.Windows.Forms
    public static class DataGridViewExtensions
        public static TRow GetSelectedRow<TRow>(this DataGridView grid, int index)
            where TRow : DataRow
            var selectedRow = grid.SelectedRows[index];
            var selectedTypedRow = (TRow)((DataRowView)selectedRow.DataBoundItem).Row;
            return selectedTypedRow;

You’d use it like this:

var selectedEmployee = dataGridView1.GetSelectedRow<CrmDataSet.EmployeeRow>(0);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s