BindingSource.AllowNew Свойство

Определение

Получает или устанавливает значение, показывающее, можно ли добавлять элементы в список с помощью метода AddNew().

public:
 virtual property bool AllowNew { bool get(); void set(bool value); };
public virtual bool AllowNew { get; set; }
member this.AllowNew : bool with get, set
Public Overridable Property AllowNew As Boolean

Значение свойства

Значение true, если можно добавить элементы в список с помощью метода AddNew(). В противном случае — значение false.

Исключения

Это свойство устанавливается в значение true, если базовый список, представляемый свойством List, имеет фиксированный размер или доступен только для чтения.

Это свойство устанавливается в значение true, и событие AddingNew не обрабатывается, когда для типа базового списка отсутствует конструктор без параметров.

Примеры

В следующем примере кода показано использование AllowNew свойства BindingSource компонента, чтобы разрешить пользователю добавлять новые элементы в базовый BindingSource список компонента. Задание этому свойству значения true приведет к тому, что связанный DataGridView элемент управления будет отображать свою строку для новых записей.

Form1()
{
   // Set up the form.
   this->Size = System::Drawing::Size( 800, 800 );
   this->Load += gcnew EventHandler( this, &Form1::Form1_Load );
   
   // Set up the RadioButton controls.
   this->allRadioBtn->Text = L"All";
   this->allRadioBtn->Checked = true;
   this->allRadioBtn->CheckedChanged += gcnew EventHandler(
      this, &Form1::allRadioBtn_CheckedChanged );
   this->allRadioBtn->Dock = DockStyle::Top;
   this->currentRadioBtn->Text = L"Current";
   this->currentRadioBtn->CheckedChanged += gcnew EventHandler(
      this, &Form1::currentRadioBtn_CheckedChanged );
   this->currentRadioBtn->Dock = DockStyle::Top;
   this->noneRadioBtn->Text = L"None";
   this->noneRadioBtn->CheckedChanged += gcnew EventHandler(
      this, &Form1::noneRadioBtn_CheckedChanged );
   this->noneRadioBtn->Dock = DockStyle::Top;
   this->buttonPanel->Controls->Add( this->allRadioBtn );
   this->buttonPanel->Controls->Add( this->currentRadioBtn );
   this->buttonPanel->Controls->Add( this->noneRadioBtn );
   this->buttonPanel->Dock = DockStyle::Bottom;
   this->Controls->Add( this->buttonPanel );
   
   // Set up the DataGridView control.
   this->customersDataGridView->AllowUserToAddRows = true;
   this->customersDataGridView->Dock = DockStyle::Fill;
   this->Controls->Add( customersDataGridView );
   
   // Add the StatusBar control to the form.
   this->Controls->Add( status );
   
   // Allow the user to add new items.
   this->customersBindingSource->AllowNew = true;
   
   // Attach an event handler for the AddingNew event.
   this->customersBindingSource->AddingNew +=
      gcnew AddingNewEventHandler(
         this, &Form1::customersBindingSource_AddingNew );
   
   // Attach an eventhandler for the ListChanged event.
   this->customersBindingSource->ListChanged +=
      gcnew ListChangedEventHandler(
         this, &Form1::customersBindingSource_ListChanged );
   
   // Set the initial value of the ItemChangedEventMode property
   // to report all ListChanged events.
   this->customersBindingSource->ItemChangedEventMode = 
     ItemChangedEventMode::All;
   
   // Attach the BindingSource to the DataGridView.
   this->customersDataGridView->DataSource =
      this->customersBindingSource;
}
public Form1()
{
    // Set up the form.
    this.Size = new Size(800, 800);
    this.Load += new EventHandler(Form1_Load);

    // Set up the DataGridView control.
    this.customersDataGridView.AllowUserToAddRows = true;
    this.customersDataGridView.Dock = DockStyle.Fill;
    this.Controls.Add(customersDataGridView);

    // Add the StatusBar control to the form.
    this.Controls.Add(status);

    // Allow the user to add new items.
    this.customersBindingSource.AllowNew = true;

    // Attach an event handler for the AddingNew event.
    this.customersBindingSource.AddingNew +=
        new AddingNewEventHandler(customersBindingSource_AddingNew);

    // Attach an eventhandler for the ListChanged event.
    this.customersBindingSource.ListChanged +=
        new ListChangedEventHandler(customersBindingSource_ListChanged);

    // Attach the BindingSource to the DataGridView.
    this.customersDataGridView.DataSource =
        this.customersBindingSource;
}
Public Sub New() 
    ' Set up the form.
    Me.Size = New Size(800, 800)
    AddHandler Me.Load, AddressOf Form1_Load
    
    ' Set up the DataGridView control.
    Me.customersDataGridView.AllowUserToAddRows = True
    Me.customersDataGridView.Dock = DockStyle.Fill
    Me.Controls.Add(customersDataGridView)
    
    ' Add the StatusBar control to the form.
    Me.Controls.Add(status)
    
    ' Allow the user to add new items.
    Me.customersBindingSource.AllowNew = True
    
    ' Attach the BindingSource to the DataGridView.
    Me.customersDataGridView.DataSource = Me.customersBindingSource

End Sub

Комментарии

Значение по умолчанию для AllowNew свойства зависит от базового типа источника данных. Если базовый список реализует IBindingList интерфейс, это свойство делегирует базовому списку. В противном случае это свойство возвращает false , если базовый список имеет какие-либо из следующих характеристик:

  • Он имеет фиксированный размер, определяемый свойством IList.IsFixedSize .

  • Он доступен только для чтения, как определено свойством IList.IsReadOnly .

  • Тип элемента не имеет конструктора без параметров.

Примечание

После установки значения этого свойства метод получения больше не будет ссылаться на вызов базового списка. Вместо этого он просто возвращает значение, которое было задано ранее до ResetAllowNew вызова метода .

Задание этого свойства вызывает событие с заданным ListChangedListChangedEventArgs.ListChangedType значением ListChangedType.Reset.

Если для свойства задано значение AllowNewtrue , а базовый тип списка не имеет конструктора без параметров, необходимо обработать AddingNew событие и создать соответствующий тип.

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

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