Unselect all rows in datagridview
Solution 1
dataGridView1.ClearSelection();
Should work. Maybe you have code that auto selects rows which is triggered?
Solution 2
An answer at NullSkull solved the problem for me which was that the cell at row 0, column 0 for the datagridview control was always selected on form load, and could not be deselected despite calling ClearSelection within the form's constructor method. I just had to call ClearSelection in the Form_Load event. http://www.nullskull.com/q/10066166/how-to-deselect-the-first-row-when-the-form-i-loaded-in-datagridview-in-windows-application.aspx
Solution 3
Since there is no answer, and I used this answer in other posts and i ran into the same issue of first row being selected and deselecting wasn't possible:
Color blue = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;
foreach (DataGridViewRow r in datagridIncome.Rows)
{
if (r.Cells[5].Value.ToString().Contains("1")) {
r.DefaultCellStyle.BackColor = blue;
r.DefaultCellStyle.SelectionBackColor = blue;
r.DefaultCellStyle.SelectionForeColor = letters;
}
else {
r.DefaultCellStyle.BackColor = red;
r.DefaultCellStyle.SelectionBackColor = red;
r.DefaultCellStyle.SelectionForeColor = letters;
}
}
This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected.
SOLUTION:
i found out why my first row was default selected and found out how to not select it by default.
By default my datagridview was the object with the first tab-stop on my windows form. Making the tab stop first on another object (maybe disabling tabstop for the datagrid at all will work to) disabled selecting the first row
Solution 4
Just use:
dgvName.ClearSelection();
Martin Ch
Updated on September 27, 2021Comments
-
Martin Ch over 2 years
I have two datagridviews, and when I click to one of them, I would like to deselect all selection in the second datagridview, I tried this, but nothing works:
firstItemsDataGridView.ClearSelection(); firstItemsDataGridView.CurrentCell = null;
not working,
firstItemsDataGridView.ClearSelection(); if (firstItemsDataGridView.Rows.Count > 0) firstItemsDataGridView[1, 0].Selected = true; firstItemsDataGridView.CurrentCell = null; firstItemsDataGridView.ClearSelection(); foreach (DataGridViewRow item in firstItemsDataGridView.Rows) { item.Selected = false; foreach (DataGridViewCell itemCell in firstItemsDataGridView.Columns) { itemCell.Selected = false; } }
not working,
firstItemsDataGridView.Rows[0,-1].Selected = true;
not working too.
I have set selecting mode to full row selection, and I have no idea how to achieve my goal.
thanks a lot!