C# – DataGridView: How to select first cell in current row when MultiSelect is true

cdatagridview

I am creating my DataGridViewEx class, inherited from DataGridView.
I want to create a method for selecting first cell in a current row, so I wrote this:

        /// <summary>
    /// The method selects first visible cell in a current row.
    /// If current row is null, nothing is done. 
    /// If any cells are selected, they are unselected before selecting first cell.
    /// </summary>
    public void SelectFirstCellInCurrentRow()
    {
        if (CurrentRow == null) return;

        ClearSelection();
        foreach (DataGridViewCell cell in CurrentRow.Cells)
        {
            if (cell.Visible)
            {
                cell.Selected = true;
                return;
            }
        }
    }

And I want to use it like this for example:

     private void btnAdd_Click(object sender, EventArgs e)
        {
            bindingSource.Add(new Customer());
            bindingSource.MoveLast();
            grid.SelectFirstCellInCurrentRow();
            grid.BeginEdit(false);
        }

My task is to add a new row to the grid and start editing its first cell.
This code works fine if grid.MultiSelect = false, but if grid.MultiSelect = true, then it doesn't work as expected: all cells are deselected, first cell of the last row is selected, but !!! the cell in last row on column that was last selected gets edited, instead of first cell!

This is how it looks:
1) I select some cells:
_http://img13.imageshack.us/img13/2528/beforeadd.gif

2) After I press Add button:
_http://img211.imageshack.us/img211/847/afteradd.gif

Thank you in advance.

PS. Why can't I add images?

Best Answer

Instead of

cell.Selected = true;

try

CurrentCell = cell;
Related Topic