DataGridView.CellContentClick 事件

定义

单击单元格的内容时发生。

C#
public event System.Windows.Forms.DataGridViewCellEventHandler CellContentClick;
C#
public event System.Windows.Forms.DataGridViewCellEventHandler? CellContentClick;

事件类型

示例

下面的代码示例为此事件提供了一个处理程序,该处理程序确定单击的单元格是链接单元格还是按钮单元格,并作为结果执行相应的操作。 此示例是类概述主题中提供的更大示例的 DataGridViewComboBoxColumn 一部分。

C#
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

    if (IsANonHeaderLinkCell(e))
    {
        MoveToLinked(e);
    }
    else if (IsANonHeaderButtonCell(e))
    {
        PopulateSales(e);
    }
}

private void MoveToLinked(DataGridViewCellEventArgs e)
{
    string employeeId;
    object value = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
    if (value is DBNull) { return; }

    employeeId = value.ToString();
    DataGridViewCell boss = RetrieveSuperiorsLastNameCell(employeeId);
    if (boss != null)
    {
        DataGridView1.CurrentCell = boss;
    }
}

private bool IsANonHeaderLinkCell(DataGridViewCellEventArgs cellEvent)
{
    if (DataGridView1.Columns[cellEvent.ColumnIndex] is
        DataGridViewLinkColumn &&
        cellEvent.RowIndex != -1)
    { return true; }
    else { return false; }
}

private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
{
    if (DataGridView1.Columns[cellEvent.ColumnIndex] is
        DataGridViewButtonColumn &&
        cellEvent.RowIndex != -1)
    { return true; }
    else { return (false); }
}

private DataGridViewCell RetrieveSuperiorsLastNameCell(string employeeId)
{

    foreach (DataGridViewRow row in DataGridView1.Rows)
    {
        if (row.IsNewRow) { return null; }
        if (row.Cells[ColumnName.EmployeeId.ToString()].Value.ToString().Equals(employeeId))
        {
            return row.Cells[ColumnName.LastName.ToString()];
        }
    }
    return null;
}

注解

单击单元格内容时发生此事件。 当用户在按钮单元格或检查框单元格具有焦点时按下并松开空格键时,也会发生这种情况;如果在按空格键的同时单击单元格内容,这些单元格类型将发生两次。

使用此事件检测 的 DataGridViewButtonCell 按钮单击次数或 的链接单击次数 DataGridViewLinkCell

对于 中的DataGridViewCheckBoxCell单击,此事件发生在检查框更改值之前,因此,如果不希望基于当前值计算预期值,通常将改为处理事件DataGridView.CellValueChanged。 由于该事件仅在提交用户指定的值时发生(通常在焦点离开单元格时发生),因此还必须处理该 DataGridView.CurrentCellDirtyStateChanged 事件。 在该处理程序中,如果当前单元格是检查框单元格,请调用 DataGridView.CommitEdit 方法并传入Commit值。

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅