将当前单元格选择更改为行选择

时间:2013-01-13 10:54:39

标签: c# winforms datagridview

我有一个Windows窗体,其中有一个DataGridView。它的属性是单元格选择,我有一个ContextMenustrip,其中有一个名为select all的菜单,当select all all时,它应该将所选单元格的DataGridView的属性更改为{{1并且选择应该在我单击的同一行上。问题是,当我单击一个单元格时,默认属性是单元格选择,当我单击选择所有FullRowSelect时,所选单元格未被选中,我必须重新选择我想要的那个行打开,当我点击特定单元格时,当我点击选择所有ContextMenustrip被点击时,应该选择同一行,我点击了单元格,这是我的代码。

ContextMenustrip

3 个答案:

答案 0 :(得分:3)

如果我正确地阅读了您的问题,您需要在单击上下文菜单的“全选”选项时选择整行。如果这是正确的,您可以尝试:

dataGridView1.SelectedCells[0].OwningRow.Selected = true;

foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
    cell.OwningRow.Selected = true;

您需要先删除以下行:

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

上面的行将把DataGridView置于全行选择模式,其中不会使用SelectedCells属性,当您单击上下文菜单中的Select All选项时,您将看到以下异常。

Index was out of range. Must be non-negative and less than the size of the collection.

整个功能应如下所示:

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
    foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        cell.OwningRow.Selected = true;
}

请注意,用户需要(左)单击要在右键单击之前选择行的单元格以显示上下文菜单。否则,选择不会改变,并且将选择先前选择的单元格行。

答案 1 :(得分:1)

更改选择模式之前选择选择的单元格,并在选择模式更改后选择这些单元格的行

var selectedCells = dataGridView1.SelectedCells;            
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

foreach (DataGridViewCell cell in selectedCells)            
    dataGridView1.Rows[cell.RowIndex].Selected = true;

为什么你必须这样做?因为DataGridView控件在选择模式更改时会清除选择。请参阅msnd上SelectionMode属性的备注:

  

更改SelectionMode属性的值将清除当前选择。

答案 2 :(得分:1)

   private void employeesDataGridView_MouseUp(object sender, MouseEventArgs e)
    {
        DataGridView.HitTestInfo hitTestInfo;
        if (e.Button == MouseButtons.Right)
        {
            hitTestInfo = employeesDataGridView.HitTest(e.X, e.Y);
            if (hitTestInfo.Type == DataGridViewHitTestType.RowHeader || hitTestInfo.Type == DataGridViewHitTestType.Cell)
            {
                if (hitTestInfo.ColumnIndex != -1)
                    employeesDataGridView.CurrentCell = employeesDataGridView[hitTestInfo.ColumnIndex, hitTestInfo.RowIndex];
                contextMenuStrip1.Show(employeesDataGridView, employeesDataGridView.PointToClient(System.Windows.Forms.Cursor.Position));
            }
        }       
    }

    private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
    {
        employeesDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        var current = employeesDataGridView.CurrentCell;
        if (current == null) return;
        if (current.ColumnIndex == -1)
            return;
        if (current.RowIndex == -1)
            return;
        employeesDataGridView[current.ColumnIndex, current.RowIndex].Selected = true;
    }

    private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e)
    {
        employeesDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
    }