When I fill a DataGridView row by row (calling it\'s add function), the top row gets blue colored. It\'s not selected because I tried ClearSelection() also but it didnt work
In Form.Shown
Event Just do a:
dataGridView1.ClearSelection();
dataGridView1.CurrentCell = null;
To achieve this along with the ClearSelection
you will need to set one more property
Try this in the DataBindingComplete
dataGridView1.ClearSelection();
dataGridView1.CurrentCell = null;
EDIT
Based on your comments you can modify the code as
if (e.KeyCode == Keys.Up && dataGridView1.CurrentCell.RowIndex == 0)
{
this.ActiveControl = textBoxPartySearch;
dataGridView1.Refresh();
dataGridView1.ClearSelection();
dataGridView1.CurrentCell = null;
e.Handled = true;
}
I tried the above methods but nothing worked for me.
Finally, I just decided to set the default colors for selected cells to be the same as non-selected cells.
Then, in the cell click method, I set them back. That way nothing appears selected until its clicked, which was sufficient for my application. Here's the code I used in the click method to set everything back to normal:
dataGridView.DefaultCellStyle.SelectionBackColor = SystemColors.Highlight;
dataGridView.DefaultCellStyle.SelectionForeColor = SystemColors.Window;
Annoyingly, the ClearSelection method actually works just fine if I put it in a button, but if I create the control which contains the datagrid, load some data into it, and then try to clear it right then, it doesn't work. I wish I knew why...
After three hours of troubleshooting this, I've figured it out: Your DataGridView
needs to be displayed on the screen before calling dataGridView.ClearSelection()
.
How I know this works:
I have two DataGridViews
, each in a different panel. Only one panel is visible at a time. In the panel that's initially visible, the DataGridView
has never ignored my call to ClearSelection()
, so I've never seen a row selected right away.
I used to populate the other DataGridView
and clear its selection before showing the panel that contains it, but that top row was always still highlighted. I changed my code to display the other panel before clearing the DataGridView
's selection, and the call to ClearSelection()
worked as it should.
Try adding ClearSelection() to VisibleChanged event as follows:
private void datagridview1_VisibleChanged(object sender, EventArgs e)
{
datagridview1.ClearSelection();
}