مشاركة عبر


كيفية القيام بما يلي: تخصيص إضافة عنصر مع BindingSource نماذج Windows

عند استخدام مكون BindingSource من أجل ربط عناصر تحكم نماذج Windows مع المصدر بيانات، قد تجد أنه من الضروري تخصيص إنشاء عناصر جديدة. يجعل مكون BindingSource هذا مباشراً وذلك بتوفير حدث AddingNew, الذي يظهر عادة عندما يحتاج عنصر التحكم المنضم إلى إنشاء عنصر جديد. يمكن أن يوفر معالج الأحداث أي سلوك مخصص مطلوب (على سبيل المثال، استدعاء أسلوب خدمة الويب أو الحصول على كائن جديد من منشئ الفئات).

ملاحظة

عند إضافة عنصر عن طريق معالجة حدث AddingNew، لا يمكن إلغاء هذه الإضافة.

مثال

المثال التالي يوضح كيفية ربط عنصر تحكم DataGridView مع منشئ الفئات باستخدام مكوّن BindingSource. عندما يقوم المستخدم بالنقر فوق عنصر التحك في صف جديدDataGridView , سيظهر الحدث AddingNew. معالج الحدث يقوم بإنشاء كائن DemoCustomer جديد, الذي تم تعيينه لخاصية AddingNewEventArgs.NewObject. هذا يؤدي إلى كائن DemoCustomer جديد يضاف إلى مكوّن القائمة BindingSource و لكي يتم عرضها في صف جديد من عنصر التحكم DataGridView.

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Data.SqlClient
Imports 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
    Inherits System.Windows.Forms.Form

    ' This is the BindingSource that will provide data for
   ' the DataGridView control.
    Private WithEvents customersBindingSource As New BindingSource()

   ' This is the DataGridView control that will display our data.
   Private customersDataGridView As New DataGridView()

   ' Set up the StatusBar for displaying ListChanged events.
   Private status As New StatusBar()

    Public Sub New()

        ' Set up the form.
        Me.Size = New Size(800, 800)
        AddHandler Me.Load, AddressOf Form1_Load
        Me.Controls.Add(status)

        ' Set up the DataGridView control.
        Me.customersDataGridView.Dock = DockStyle.Fill
        Me.Controls.Add(customersDataGridView)

    End Sub

    Private Sub Form1_Load( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs)

        ' Add a DemoCustomer to cause a row to be displayed.
        Me.customersBindingSource.AddNew()

        ' Bind the BindingSource to the DataGridView 
        ' control's DataSource.
        Me.customersDataGridView.DataSource = Me.customersBindingSource

    End Sub

   ' This event handler provides custom item-creation behavior.
    Private Sub customersBindingSource_AddingNew( _
    ByVal sender As Object, _
    ByVal e As AddingNewEventArgs) _
    Handles customersBindingSource.AddingNew

        e.NewObject = DemoCustomer.CreateNewCustomer()

    End Sub

    ' This event handler detects changes in the BindingSource 
   ' list or changes to items within the list.
    Private Sub customersBindingSource_ListChanged( _
    ByVal sender As Object, _
    ByVal e As ListChangedEventArgs) _
    Handles customersBindingSource.ListChanged

        status.Text = e.ListChangedType.ToString()

    End Sub

   <STAThread()>  _
   Shared Sub Main()
      Application.EnableVisualStyles()
      Application.Run(New Form1())
    End Sub
End Class

' This class implements a simple customer type.
Public Class DemoCustomer

    ' These fields hold the values for the public properties.
    Private idValue As Guid = Guid.NewGuid()
    Private customerName As String = String.Empty
    Private companyNameValue As String = String.Empty
    Private phoneNumberValue As String = String.Empty

    ' The constructor is private to enforce the factory pattern.
    Private Sub New()
        customerName = "no data"
        companyNameValue = "no data"
        phoneNumberValue = "no data"
    End Sub

    ' This is the public factory method.
    Public Shared Function CreateNewCustomer() As DemoCustomer
        Return New DemoCustomer()
    End Function

    ' This property represents an ID, suitable
    ' for use as a primary key in a database.
    Public ReadOnly Property ID() As Guid
        Get
            Return Me.idValue
        End Get
    End Property

    Public Property CompanyName() As String
        Get
            Return Me.companyNameValue
        End Get

        Set(ByVal value As String)
            Me.companyNameValue = Value
        End Set
    End Property

    Public Property PhoneNumber() As String
        Get
            Return Me.phoneNumberValue
        End Get

        Set(ByVal value As String)
            Me.phoneNumberValue = Value
        End Set
    End Property
End Class
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;
        }
    }
}
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Drawing;
using namespace System::Globalization;
using namespace System::Windows::Forms;

namespace DataConnectorAddingNewExample
{
    // This class implements a simple customer type.
    public ref class DemoCustomer
    {
    private:
        // These fields hold the values for the public properties.
        Guid idValue;
        String^ customerName;
        String^ companyNameValue;
        String^ phoneNumberValue;

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

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

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

        property String^ CompanyName 
        {
            String^ get()
            {
                return this->companyNameValue;
            }

            void set(String^ value)
            {
                this->companyNameValue = value;
            }
        }

        property String^ PhoneNumber 
        {
            String^ get()
            {
                return this->phoneNumberValue;
            }

            void set(String^ value)
            {
                this->phoneNumberValue = value;
            }
        }
    };

    // This form demonstrates using a BindingSource to provide
    // data from a collection of custom types 
    // to a DataGridView control.
    public ref class MainForm: public System::Windows::Forms::Form
    {
    private:

        // This is the BindingSource that will provide data for
        // the DataGridView control.
        BindingSource^ customersBindingSource;

        // This is the DataGridView control 
        // that will display our data.
        DataGridView^ customersDataGridView;

        // Set up the StatusBar for displaying ListChanged events.
        StatusBar^ status;
    
    public:

        MainForm()
        {
            customersBindingSource = gcnew BindingSource;
            customersDataGridView = gcnew DataGridView;
            status = gcnew StatusBar;

            // Set up the form.
            this->Size = System::Drawing::Size(600, 400);
            this->Text = "BindingSource.AddingNew sample";
            this->Load += 
                gcnew EventHandler(this, &MainForm::OnMainFormLoad);
            this->Controls->Add(status);

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

            // Attach an event handler for the AddingNew event.
            this->customersBindingSource->AddingNew += 
                gcnew AddingNewEventHandler(this, 
                &MainForm::OnCustomersBindingSourceAddingNew);

            // Attach an event handler for the ListChanged event.
            this->customersBindingSource->ListChanged += 
                gcnew ListChangedEventHandler(this, 
                &MainForm::OnCustomersBindingSourceListChanged);
        }

    private:

        void OnMainFormLoad(Object^ sender, 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 OnCustomersBindingSourceAddingNew(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 OnCustomersBindingSourceListChanged(Object^ sender, 
            ListChangedEventArgs^ e)
        {   
            status->Text = Convert::ToString(e->ListChangedType, 
                CultureInfo::CurrentCulture);
        }
    };
}

[STAThread]
int main()
{
    Application::EnableVisualStyles();
    Application::Run(gcnew DataConnectorAddingNewExample::MainForm);
}

التحويل البرمجي للتعليمات البرمجية

يتطلب هذا المثال:

  • مراجع عن تجميعات النظام و تجميعات System, System.Data, System.Drawing ,و System.Windows.Forms.

للحصول على المزيد من المعلومات حول إنشاء هذا المثال من خط أوامر Visual Basic أو #Visual C، راجع الإنشاء من سطر الأوامر (Visual Basic) أو إنشاء سطر الأوامر باستخدام csc.exe. يمكنك أيضاً بناء هذا المثال في Visual Studio عن طريق لصق التعليمات البرمجية في مشروع جديد. لمزيد من المعلومات، راجع: كيفية القيام بما يلي: ترجمة و تشغيل مثال التعليمات برمجية لنماذج Windows الكامل باستخدام ‏‫Visual Studio.

راجع أيضًا:

المهام

كيفية القيام بما يلي: قم بربط عنصر تحكم Windows Forms إلى النوع

المرجع

BindingNavigator

DataGridView

BindingSource

موارد أخرى

مكوّن BindingSource