Show / Hide Table of Contents

Практическое руководство. Настройка дополнений к элементам с помощью элемента управления BindingSource в Windows Forms

При использовании компонента BindingSource для привязки элемента управления Windows Forms к источнику данных может потребоваться настроить создание новых элементов. Компонент BindingSource упрощает эту процедуру, предоставляя событие AddingNew , которое обычно происходит, когда связанный элемент управления должен создать новый элемент. Обработчик событий может обеспечивать любое необходимое поведение (например, вызов метода веб-службы или получение нового объекта из фабрики класса).

Note

Добавление элемента с помощью события AddingNew отменить нельзя.

Пример

В примере ниже показано, как связать элемент управления DataGridView с фабрикой класса с помощью компонента BindingSource . Когда пользователь щелкает новую строку элемента управления DataGridView , вызывается событие AddingNew . Обработчик событий создает объект DemoCustomer , который присваивается свойству AddingNewEventArgs.NewObject . В результате новый объект DemoCustomer добавляется к списку компонентов BindingSource и отображается в новой строке элемента управления DataGridView .

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Windows.Forms;

// This form demonstrates using a BindingSource to provide
// data from a collection of custom types to a DataGridView control.
public class Form1 : System.Windows.Forms.Form
{
    // This is the BindingSource that will provide data for
    // the DataGridView control.
    private BindingSource customersBindingSource = new BindingSource();

    // This is the DataGridView control that will display our data.
    private DataGridView customersDataGridView = new DataGridView();

    // Set up the StatusBar for displaying ListChanged events.
    private StatusBar status = new StatusBar();


    public Form1()
    {
        // Set up the form.
        this.Size = new Size(800, 800);
        this.Load += new EventHandler(Form1_Load);
        this.Controls.Add(status);

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

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

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

    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        // Add a DemoCustomer to cause a row to be displayed.
        this.customersBindingSource.AddNew();

        // Bind the BindingSource to the DataGridView 
        // control's DataSource.
        this.customersDataGridView.DataSource = 
            this.customersBindingSource;
    }

    // This event handler provides custom item-creation behavior.
    void customersBindingSource_AddingNew(
        object sender, 
        AddingNewEventArgs e)
    {
        e.NewObject = DemoCustomer.CreateNewCustomer();
    }

    // This event handler detects changes in the BindingSource 
    // list or changes to items within the list.
    void customersBindingSource_ListChanged(
        object sender, 
        ListChangedEventArgs e)
    {
        status.Text = e.ListChangedType.ToString();
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }
}

// This class implements a simple customer type.
public class DemoCustomer
{
    // These fields hold the values for the public properties.
    private Guid idValue = Guid.NewGuid();
    private string customerName = String.Empty;
    private string companyNameValue = String.Empty;
    private string phoneNumberValue = String.Empty;

    // The constructor is private to enforce the factory pattern.
    private DemoCustomer()
    {
        customerName = "no data";
        companyNameValue = "no data";
        phoneNumberValue = "no data";
    }

    // This is the public factory method.
    public static DemoCustomer CreateNewCustomer()
    {
        return new DemoCustomer();
    }

    // This property represents an ID, suitable
    // for use as a primary key in a database.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }

    public string CompanyName
    {
        get
        {
            return this.companyNameValue;
        }

        set
        {
            this.companyNameValue = value;
        }
    }

    public string PhoneNumber
    {
        get
        {
            return this.phoneNumberValue;
        }

        set
        {
            this.phoneNumberValue = value;
        }
    }
}

Компиляция кода

Для этого примера требуются:

  • ссылки на сборки System, System.Data, System.Drawing и System.Windows.Forms.

Сведения о выполнении сборки этого примера из командной строки для Visual Basic или Visual C#, см. в разделе построение из командной строки или командной строки создания с помощью csc.exe. Можно также сборке этого примера в Visual Studio путем вставки кода в новый проект.

См. также

  • BindingNavigator
  • DataGridView
  • BindingSource
  • Компонент BindingSource
  • Практическое руководство. Связывание элемента управления с типом в Windows Forms
Back to top Неофициальная документация по .NET на русском языке. Лицензия: CC-BY 4.0. Основано на документации по .NET с Microsoft Docs
Generated by DocFX