How can one disable the first autoselect in a VS datagridview?
Asked Answered
M

11

11

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.

Milldam answered 19/9, 2012 at 12:29 Comment(1)
It`s strange behavior, It must not select value automatically, can you show your code, it might help to grasp what the error is.Dravidian
R
2

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.

Remontant answered 14/6, 2013 at 15:8 Comment(8)
Heh heh to be completely honest my friend I already quit my job by now so in theory it does not help :P But still, very interesting, thank you. It is very weird that something so seemingly simple needs a solution so unwieldy. One of the reasons I do not like coding in C# - Too much going on behind the scenes of which you have no immediate control over. Though again, thanks for the response, maybe this will help other unfortunate souls in the future!Milldam
@Pino lol!! awesome, have a good one mate. Solutions round undesired behavior in things like DataGridViews seems to take too much effort, I'm always hoping for a more elegant solution. Sometimes it feels like I'm working with a Heath Robinson machine, but then used in the way they expect to be used the performance can be excellent.Remontant
I tried your solution, though it didn't seem to actually work.Ticking
@Ticking very sorry the solution didn't work for you. I tried it just now with a new WinForm project both .Net3.5 and .Net4 which worked ok but if I may ask what type of malfunction was there? Was it just still selecting the first row?, or was it throwing an exception or something?Remontant
@user2433394 The first row was is still being selected, yes. Though I found an alternative solution for my problem that worked out well. I just saved the selection before I modify the list, and if the selection does not match the old selection, I revert it back to what it was. So this solution works when you have a single place that data is being added, so you can do a setup before it's added to handle the auto selection. Yours would be a little more ideal, intercepting it at the source.Ticking
@Ticking nice one for your solution. I'm wondering if my mistake is presuming when the data binding has finished. If there's asynchronicity then it might be best to /also/ call ClearSelectionAndResetSuppression() off the DataBindingComplete event.Remontant
@user2433394 Wait, so in my test case the first data is added after the dataSource has been bound, and that's when the auto selection happens. Yours only handles it when the dataSource is bound/rebound, right? I don't rebind the dataSource, I add data directly to it and the changes are reflected in the dataGridView I'm using.Ticking
@Ticking yes binding and rebinding was my situation :)Remontant
H
9

You should call: ClearSelection after event: DataBindingComplete

Hardej answered 13/3, 2014 at 9:35 Comment(2)
This would be the ideal solution but it doesn't suppress SelectionChanged event which is still triggered for the 'phantom' selectionRemontant
If you're not using data binding then call ClearSelection the first time the dataGrid becomes visible.Atavistic
R
2

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.

Remontant answered 14/6, 2013 at 15:8 Comment(8)
Heh heh to be completely honest my friend I already quit my job by now so in theory it does not help :P But still, very interesting, thank you. It is very weird that something so seemingly simple needs a solution so unwieldy. One of the reasons I do not like coding in C# - Too much going on behind the scenes of which you have no immediate control over. Though again, thanks for the response, maybe this will help other unfortunate souls in the future!Milldam
@Pino lol!! awesome, have a good one mate. Solutions round undesired behavior in things like DataGridViews seems to take too much effort, I'm always hoping for a more elegant solution. Sometimes it feels like I'm working with a Heath Robinson machine, but then used in the way they expect to be used the performance can be excellent.Remontant
I tried your solution, though it didn't seem to actually work.Ticking
@Ticking very sorry the solution didn't work for you. I tried it just now with a new WinForm project both .Net3.5 and .Net4 which worked ok but if I may ask what type of malfunction was there? Was it just still selecting the first row?, or was it throwing an exception or something?Remontant
@user2433394 The first row was is still being selected, yes. Though I found an alternative solution for my problem that worked out well. I just saved the selection before I modify the list, and if the selection does not match the old selection, I revert it back to what it was. So this solution works when you have a single place that data is being added, so you can do a setup before it's added to handle the auto selection. Yours would be a little more ideal, intercepting it at the source.Ticking
@Ticking nice one for your solution. I'm wondering if my mistake is presuming when the data binding has finished. If there's asynchronicity then it might be best to /also/ call ClearSelectionAndResetSuppression() off the DataBindingComplete event.Remontant
@user2433394 Wait, so in my test case the first data is added after the dataSource has been bound, and that's when the auto selection happens. Yours only handles it when the dataSource is bound/rebound, right? I don't rebind the dataSource, I add data directly to it and the changes are reflected in the dataGridView I'm using.Ticking
@Ticking yes binding and rebinding was my situation :)Remontant
C
0

you can deselect it in your form_load event like

  private void Form1_Load(object sender, EventArgs e)
        {
                dataGridView1.Rows[0].Selected = false;
        }
Carbonize answered 19/9, 2012 at 12:49 Comment(2)
This might fix the symptom, it doesn't address the underlying problemLaquitalar
To address as to why I did not choose this answer: It does not fix the symptom if the datasource is set after user interaction instead of form loading.Milldam
A
0

To load the grid without any selection, you can use this code snippet.

 GridView.CurrentCell = null;

This will load it plain, without any selection. Add this after assigning data-source to the grid.

Adscription answered 25/2, 2014 at 7:27 Comment(0)
T
0

Make sure your are NOT calling the method to load the data from the form constructor. If you call it from the Form.load()

also after the myDataGridView is loaded do this

myDataGridView.Rows[0].Selected = false;

Tojo answered 1/11, 2015 at 19:52 Comment(0)
E
0

This worked for me:

Deregister the SelectionChanged event just before binding the data and then re-register the event. Maybe you should delete the registration of the event in the designer and register the event manually in your code.

myDGV.SelectionChanged -= new System.EventHandler(this.myDGV_SelectionChanged);

Eastward answered 5/5, 2017 at 16:51 Comment(0)
R
0

Your experience may vary, but in my work I frequently fight this when the grid first loads, and although many solutions have been found to be acceptable (and far more are just ludicrous), they don't all work in every scenario. The one solution I find that works the most (for me, again your experience and scenarios may vary) is handling DataGridView.VisibleChanged:

    public ThingWithGrid() {
        Grid.VisibleChanged += Grid_VisibleChanged;
    }

    private void Grid_VisibleChanged(object sender, EventArgs e)
    {
        UpdateSelectedRows(InitialSelection);
        Grid.VisibleChanged -= Grid_VisibleChanged;
    }
Repurchase answered 27/1, 2019 at 18:12 Comment(0)
S
0

I think the simplest solution is to remove the eventhandler, assign the new datasource, clear the selection and reassign the eventhandler:

private void updateDataGridViewDataSource(%whatevertype% %whatever%) {
    dataGridView1.SelectionChanged -= new System.EventHandler(this.dataGridView1_SelectionChanged);
    dataGridView1.DataSource = %whatever%
    dataGridView1.ClearSelection();
    dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
}
Sacken answered 4/5, 2021 at 13:23 Comment(0)
R
0

For my case, a more simple solution was enough, in my DataGridView_DataBindingComplete handler:

DataGridView.ClearSelection();
if (DataGridView.Focused)
    DataGridView.DataBindingComplete -= DataGridView_DataBindingComplete;
Ringsmuth answered 13/1, 2022 at 21:27 Comment(0)
F
0

The solution is based in put the .ClearSelection() the neccesary times. If you check the method while enter, you can intuitive when is necessary insert, in my case, i load my rows in my data grid view when i click button on menu in my aplication, immediatly show the form and the first row is selected, but if i check the times SelectionChanged() is enter, i can clean selection, but only the neccesary times.

 Private veces_entrando As Integer = 0

 Private Sub DGVLista_SelectionChanged(sender As Object, e As EventArgs) Handles DGVLista.SelectionChanged

     veces_entrando = veces_entrando + 1

     If veces_entrando < 2 Then
        DGVLista.ClearSelection()
     End If

 End Sub
Fealty answered 5/7 at 13:28 Comment(0)
M
-1

Just add SelectedItem="-1", this will do the trick

<DataGrid Name="dataGrid" SelectedItem="-1" />
Minelayer answered 9/4, 2015 at 23:50 Comment(1)
It's not tagged, but the question is a WinForms issue.Barbican

© 2022 - 2024 — McMap. All rights reserved.