I have created an application in Visual Studio (C#) that makes use of a datagridview. Now, when I assign the DataSource of that datagridview, it automatically selects the first row, and executes my code for selection. Since I frequently reassign that datasource, this is not desireable. Is there any way to change it so it doesn't automatically make that first select, and only relies on the user's selections?
Thanks!
In response to the comment of Darshan Joshi: Apart from the auto-generated code, the only thing altered on the datagridview is setting AutoGenerateColumns to false, and setting the DataSource property. I've placed a MessageBox.Show in my selectionchanged delegate, and it seems it even gets called thrice every time the datasource is set. Once just before the data is loaded, and twice after.
I can't set selected to false on load, since the datasource is set after certain user actions, not on initialization.
You should call: ClearSelection after event: DataBindingComplete
I had the same problem and here is my solution.
The tricky part was finding where to clear the selection... We can only clear the selection after the selection has been set by the DataGridView. At first the selection is only ready to be cleared in the Form.Load event, but subsiquent settings of the DataGridView.DataSource the selection is ready to be cleared straight after the DataSource assignment.
public class DataGridView_AutoSelectSuppressed : DataGridView
{
private bool SuppressAutoSelection { get; set; }
public DataGridView_AutoSelectSuppressed() : base()
{
SuppressAutoSelection = true;
}
public new /*shadowing*/ object DataSource
{
get
{
return base.DataSource;
}
set
{
SuppressAutoSelection = true;
Form parent = this.FindForm();
// Either the selection gets cleared on form load....
parent.Load -= parent_Load;
parent.Load += parent_Load;
base.DataSource = value;
// ...or it gets cleared straight after the DataSource is set
ClearSelectionAndResetSuppression();
}
}
protected override void OnSelectionChanged(EventArgs e)
{
if (SuppressAutoSelection)
return;
base.OnSelectionChanged(e);
}
private void ClearSelectionAndResetSuppression()
{
if (this.SelectedRows.Count > 0 || this.SelectedCells.Count > 0)
{
this.ClearSelection();
SuppressAutoSelection = false;
}
}
private void parent_Load(object sender, EventArgs e)
{
ClearSelectionAndResetSuppression();
}
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With