Winforms, DataGridViews and overriding events.

WinForms are archaic and outdated with the new hotness that is WPF (not really), but I still use them.  Not often enough to know much in detail about them, but enough to get myself into trouble.

I made a small app with a data entry/update form and then on another tab added a DataGridView that would display the entered data.  The nice thing about the DataGridView in WinForms as opposed to working with web controls is that you get things like sorting for free when you click on a column header.

My problem came about when I wanted to give the user the ability to click on a row in the grid and have that record load itself into the entry form on the other tab.  I overrode the CellMouseClick event and loaded the record based on the key from that row, but that in turn killed the auto-sorting of the grid when you clicked on the header.

private void emplGrid_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            gridSelection = emplGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
            tabControl1.SelectTab("tabPage1");
            FindLoadEmployee(sender);
        }

Luckily I came to the quick conclusion that I could tell when the header cells were being clicked based on their row index and in that case a simple return statement took care of the problem.

private void emplGrid_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            gridSelection = emplGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
            tabControl1.SelectTab("tabPage1");
            FindLoadEmployee(sender);
        }

There’s probably a better way to do this or a better event to utilize given that I’m not really a WinForms developer and just sort of hack away at this, but this seemed to work for me without much issue.

Leave a Reply

Your email address will not be published. Required fields are marked *