Akshay J
Akshay J

Reputation: 5458

Datagridview Cell Selected After ClearSelection

I have been frustrated by this weird behavior of DataGridView.

When its databind-ed, one cell gets selected even when the grid does not have focus. I have adopted certain workarounds like this

this.ActiveControl = textBoxPartySearch;
 dataGridView1.Refresh();
 dataGridView1.ClearSelection();
 dataGridView1.CurrentCell = null;
 e.Handled = true;

as suggested in this question of mine : Remove blue colored row from DataGridView WinForms

But this workaround does not work sometimes and making the code messy.

Is there any other free datagridview available that does not have this problem ?

Upvotes: 5

Views: 7622

Answers (4)

Marco Hansma
Marco Hansma

Reputation: 171

This works for me:

In the constructor, after the binding is set, add a handler to the DataBindingComplete event:

dgvCommandos.DataSource = systeemCommandos; // = my List<> of objects
dgvCommandos.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgvCommandos_DataBindingComplete);

The handler:

void dgvCommandos_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dgvCommandos.ClearSelection();
}

If you intend to select a row (e.g. after adding/inserting a new object), simply set:

dgvCommandos.Rows[insertPos].Selected = true;

Upvotes: 2

joaopintocruz
joaopintocruz

Reputation: 291

I had this problem and managed to solve it by adding myDataGridView.ClearSelection(); at the end of every coded Event.

At the beginning just by having it at the end of my DataBind() method was enough. Then I added some custom behaviors for row painting and other stuff and it stopped working (i.e., always had first row selected).

So I'd say if you added any custom Event, that may be the reason.

Upvotes: 2

Bassam Bsata
Bassam Bsata

Reputation: 1135

gvDataSources.CurrentCell.IsCurrent=false;
gvDataSources.CurrentRow.IsCurrent = false;

Upvotes: 0

Denish
Denish

Reputation: 983

Change the way you are binding the grid.

First prepare datatable and then assign it to datagridview.

Upvotes: 0

Related Questions