DataGridView.CellValueNeeded 事件

定义

在以下情况下发生:当 DataGridView 控件的 VirtualMode 属性为 true,并且 DataGridView 只有在单元格中有值的情况下才格式化和显示单元格时。

C#
public event System.Windows.Forms.DataGridViewCellValueEventHandler CellValueNeeded;
C#
public event System.Windows.Forms.DataGridViewCellValueEventHandler? CellValueNeeded;

事件类型

示例

下面的代码示例处理 CellValueNeeded 事件,以使用正整数填充单元格。 此示例是参考主题中提供的更大示例的 VirtualMode 一部分。

C#
#region "data store maintance"
const int initialValue = -1;

private void dataGridView1_CellValueNeeded(object sender,
    DataGridViewCellValueEventArgs e)
{
    if (store.ContainsKey(e.RowIndex))
    {
        // Use the store if the e value has been modified 
        // and stored.            
        e.Value = store[e.RowIndex];
    }
    else if (newRowNeeded && e.RowIndex == numberOfRows)
    {
        if (dataGridView1.IsCurrentCellInEditMode)
        {
            e.Value = initialValue;
        }
        else
        {
            // Show a blank value if the cursor is just resting
            // on the last row.
            e.Value = String.Empty;
        }
    }
    else
    {
        e.Value = e.RowIndex;
    }
}

private void dataGridView1_CellValuePushed(object sender,
    DataGridViewCellValueEventArgs e)
{
    store.Add(e.RowIndex, int.Parse(e.Value.ToString()));
}
#endregion

private Dictionary<int, int> store = new Dictionary<int, int>();

注解

在虚拟模式下使用此事件在单元格中填充来自自定义数据存储的数据,而不会导致行不共享。 有关行共享的详细信息,请参阅缩放 Windows 窗体 DataGridView 控件的最佳做法。 有关虚拟模式的详细信息,请参阅 Windows 窗体 DataGridView 控件中的虚拟模式

若要将用户指定的值添加到自定义数据存储,请处理 CellValuePushed 事件。

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

适用于

产品 版本
.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

另请参阅