In my WinForms I have DataGridView
. I wanted to select full row at once so I set SelectionMode
as FullRowSelect
. And now I have problem, b
This work for me for clear selection on databind
Protected Sub GridCancel_DataBinding(sender As Object, e As EventArgs) Handles GridCancel.DataBinding
GridCancel.SelectedIndex = -1
End Sub
Try This may be helpful
private void dgv_order_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dgv_order.CurrentCell.Selected = false;
dgv_order.ClearSelection();
}
Just put dataGridView1.ClearSelection();
in load event of the form.
You can call dataGridView.ClearSelection() method inside form_Load event like this...
private void Form1_Load(object sender, EventArgs e)
{
// You will get selectedCells count 1 here
DataGridViewSelectedCellCollection selectedCells = dataGridView.SelectedCells;
// Call clearSelection
dataGridView.ClearSelection();
// Now You will get selectedCells count 0 here
selectedCells = dataGridViewSchedule.SelectedCells;
}
You should try to put in Shown event datagridView.ClearCelection()
and also datagridView.CurrentCell=null
and for example if you want to select row for deleting or changing informations just do if(datagridView.CurrentCell==null){
MessageBox.Show("You must select row");}
it works for me
Sometimes, when you reload your form without closing your program, the first row will be highlighted. But it will not be selected, and you will get -1 for selected row index.
You can do it just like this:
1. Store default styles when the form is loading:
Public Class aRoots
Dim df1, df2, df3, df4 As Color
Private Sub aRoots_Load(sender As Object, e As EventArgs) Handles Me.Load
df1 = DGV_Root.DefaultCellStyle.SelectionBackColor
df2 = DGV_Root.DefaultCellStyle.BackColor
df3 = DGV_Root.DefaultCellStyle.SelectionForeColor
df4 = DGV_Root.DefaultCellStyle.ForeColor
2. Change cell styles when interacting with datagridview:
Private Sub LoadRoot()
For i = 0 To 5
DGV_Root.Rows.Add()
For j = 0 To 3
DGV_Root.Item(j, i).Value = ...
Next
Next
'DGV_Root.ClearSelection() ==> instead of this use 2 lines below
DGV_Root.DefaultCellStyle.SelectionBackColor = df2
DGV_Root.DefaultCellStyle.SelectionForeColor = df4
End Sub
3. Change cell styles to default when selection is being changed like cell_click or cell_double click:
Private Sub DGV_Root_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DGV_Root.CellMouseClick
DGV_Root.DefaultCellStyle.SelectionBackColor = df1
DGV_Root.DefaultCellStyle.SelectionForeColor = df3
...
End Sub
4. restore all to default when u want to close form:
Private Sub PbClose_Click(sender As Object, e As EventArgs) Handles PbClose.Click
BtnCancel.PerformClick()
DGV_Root.DefaultCellStyle.SelectionBackColor = df1
DGV_Root.DefaultCellStyle.BackColor = df2
DGV_Root.DefaultCellStyle.SelectionForeColor = df3
DGV_Root.DefaultCellStyle.ForeColor = df4
Me.Close()
End Sub
Hope this help you guys.