Поделиться через


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 будет вызван.

Установка этого свойства вызывает событие с ListChangedEventArgs.ListChangedType заданным ListChanged значением ListChangedType.Reset.

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

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

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