DataGridViewCell.InitializeEditingControl Метод

Определение

Инициализирует элемент управления, используемый для изменения ячейки.

public:
 virtual void InitializeEditingControl(int rowIndex, System::Object ^ initialFormattedValue, System::Windows::Forms::DataGridViewCellStyle ^ dataGridViewCellStyle);
public virtual void InitializeEditingControl(int rowIndex, object initialFormattedValue, System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle);
public virtual void InitializeEditingControl(int rowIndex, object? initialFormattedValue, System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle);
abstract member InitializeEditingControl : int * obj * System.Windows.Forms.DataGridViewCellStyle -> unit
override this.InitializeEditingControl : int * obj * System.Windows.Forms.DataGridViewCellStyle -> unit
Public Overridable Sub InitializeEditingControl (rowIndex As Integer, initialFormattedValue As Object, dataGridViewCellStyle As DataGridViewCellStyle)

Параметры

rowIndex
Int32

Отсчитываемый от нуля индекс строки расположения ячейки.

initialFormattedValue
Object

Значение Object , отображаемое ячейкой при запуске редактирования.

dataGridViewCellStyle
DataGridViewCellStyle

Объект, DataGridViewCellStyle представляющий стиль ячейки.

Исключения

Нет связанного DataGridView элемента управления редактирования или если он присутствует, он не имеет связанного элемента управления редактирования.

Примеры

В следующем примере кода показано, как переопределить InitializeEditingControl метод в простом классе, наследуемом DataGridViewTextBoxCell от класса. Этот пример является частью более крупного примера кода, предоставленного в разделе "Практическое руководство. Элементы управления узлами в ячейках DataGridView в Windows Forms".

public class CalendarCell : DataGridViewTextBoxCell
{

    public CalendarCell()
        : base()
    {
        // Use the short date format.
        this.Style.Format = "d";
    }

    public override void InitializeEditingControl(int rowIndex, object 
        initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
    {
        // Set the value of the editing control to the current cell value.
        base.InitializeEditingControl(rowIndex, initialFormattedValue, 
            dataGridViewCellStyle);
        CalendarEditingControl ctl = 
            DataGridView.EditingControl as CalendarEditingControl;
        // Use the default row value when Value property is null.
        if (this.Value == null)
        {
            ctl.Value = (DateTime)this.DefaultNewRowValue;
        }
        else
        {
            ctl.Value = (DateTime)this.Value;
        }
    }

    public override Type EditType
    {
        get
        {
            // Return the type of the editing control that CalendarCell uses.
            return typeof(CalendarEditingControl);
        }
    }

    public override Type ValueType
    {
        get
        {
            // Return the type of the value that CalendarCell contains.
            
            return typeof(DateTime);
        }
    }

    public override object DefaultNewRowValue
    {
        get
        {
            // Use the current date and time as the default value.
            return DateTime.Now;
        }
    }
}
Public Class CalendarCell
    Inherits DataGridViewTextBoxCell

    Public Sub New()
        ' Use the short date format.
        Me.Style.Format = "d"
    End Sub

    Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _
        ByVal initialFormattedValue As Object, _
        ByVal dataGridViewCellStyle As DataGridViewCellStyle)

        ' Set the value of the editing control to the current cell value.
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _
            dataGridViewCellStyle)

        Dim ctl As CalendarEditingControl = _
            CType(DataGridView.EditingControl, CalendarEditingControl)

        ' Use the default row value when Value property is null.
        If (Me.Value Is Nothing) Then
            ctl.Value = CType(Me.DefaultNewRowValue, DateTime)
        Else
            ctl.Value = CType(Me.Value, DateTime)
        End If
    End Sub

    Public Overrides ReadOnly Property EditType() As Type
        Get
            ' Return the type of the editing control that CalendarCell uses.
            Return GetType(CalendarEditingControl)
        End Get
    End Property

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            ' Return the type of the value that CalendarCell contains.
            Return GetType(DateTime)
        End Get
    End Property

    Public Overrides ReadOnly Property DefaultNewRowValue() As Object
        Get
            ' Use the current date and time as the default value.
            Return DateTime.Now
        End Get
    End Property

End Class

Комментарии

Как метод оптимизации, обычно все ячейки одного типа и в одном и том же DataGridView совместном использовании одного размещенного элемента управления редактирования. Однако перед использованием элемента управления ячейкой его необходимо инициализировать методом InitializeEditingControl . При первом вызове этот метод добавляет элемент управления в список элементов управления редактирования в родительском элементе DataGridViewуправления. Он также инициализирует некоторые визуальные свойства ячейки. Например, InitializeEditingControl задает цвет фона области редактирования в соответствии с заданным параметром стиля ячейки. Последующие вызовы ничего не делают InitializeEditingControl .

Производные классы используют этот метод для размещения экземпляра класса, соответствующего Control их типу. Например, таблица, содержащая один или несколько DataGridViewTextBoxCell объектов, вызывает этот метод, чтобы добавить один TextBox элемент управления редактирования DataGridViewв владение.

Применяется к

См. также раздел