13 May 2009

Clear the initial Selection on the DataGridView in Windows App

I have been battling with disabling the selection of the first row in a Windows App datagridview and I tried so many solutions including having code in event handlers to solve the problem.
For example, I had
<DataGridViewName>_Selection changed where I had something like

if (SelectionAllowed)
if (<DataGridViewName>.CurrentRow != null)

SelectionAllowed is defined as a Boolean variable which I was set to true on a button click or when populating the DataGridView. This worked but had some issues.

Now I came up with a solution which, I think, would work for all property settings of the DataGridView. Mine has the following properties
MultiSelect = false
SelectionMode = FullRowSelect

What you need is
<DataGridViewName>_CellClick event handler
<DataGridViewName>_VisibleChanged event handler

In VisibleChanged handler

In _CellClick handler

if (
<DataGridViewName>.CurrentRow != null)
// Whatever you wanted to do in here

That's it... nothing more.

Note: I have only tested this in my situation. It might not work in yours.