简体   繁体   中英

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?

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 (ie, always had first row selected).

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

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 (eg after adding/inserting a new object), simply set:

dgvCommandos.Rows[insertPos].Selected = true;
gvDataSources.CurrentCell.IsCurrent=false;
gvDataSources.CurrentRow.IsCurrent = false;

Change the way you are binding the grid.

First prepare datatable and then assign it to datagridview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM