C# DataGridView:当 MultiSelect 为 true 时如何选择当前行中的第一个单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/787743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:10:39  来源:igfitidea点击:

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

c#datagridview

提问by nightcoder

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:

我正在创建从 DataGridView 继承的 DataGridViewEx 类。
我想创建一个方来选择当前行中的第一个单元格,所以我写了这个:

        /// <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!

我的任务是向网格添加新行并开始编辑其第一个单元格。
如果 grid.MultiSelect = false,此代码工作正常,但如果 grid.MultiSelect = true,则它不会按预期工作:取消选择所有单元格,选择最后一行的第一个单元格,但是!!!最后选择的列的最后一行中的单元格被编辑,而不是第一个单元格!

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

这是它的外观:
1)我选择了一些单元格
:_http://img13.imageshack.us/img13/2528/beforeadd.gif

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

2)按下添加按钮后
:_http://img211.imageshack.us/img211/847/afteradd.gif

Thank you in advance.

先感谢您。

PS. Why can't I add images?

附注。为什么我不能添加图像?

采纳答案by Arnold Spence

Instead of

代替

cell.Selected = true;

try

尝试

CurrentCell = cell;