Show / Hide Table of Contents

Практическое руководство. Связывание элемента управления с объектом-фабрикой в Windows Forms

При создании элементов управления, взаимодействующих с данными, иногда требуется привязать элемент управления к объекту или методу, создающему другие объекты. Такой объект или метод называется фабрикой. Источник данных может быть, например, возвращаемым значением вызова метода, а не объектом в памяти или типом. Можно привязать элемент управления к такому типу источника данных при условии, что источник возвращает коллекцию.

Элемент управления можно легко привязать к объекту фабрики с помощью элемента управления BindingSource.

Пример

В примере ниже показано, как связать элемент управления DataGridView с методом фабрики с помощью элемента управления BindingSource. Метод фабрики называется GetOrdersByCustomerId и возвращает все заказы для данного клиента в базе данных Northwind.

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

// This form demonstrates using a BindingSource to bind to a factory
// object. 
public class Form1 : System.Windows.Forms.Form
{
    // This is the TextBox for entering CustomerID values.
    private TextBox customerIdTextBox = new TextBox();

    // This is the DataGridView that displays orders for the 
    // specified customer.
    private DataGridView customersDataGridView = new DataGridView();

    // This is the BindingSource for binding the database query
    // result set to the DataGridView.
    private BindingSource ordersBindingSource = new BindingSource();

    public Form1()
    {
        // Set up the CustomerID TextBox.
        this.customerIdTextBox.Location = new Point(100, 200);
        this.customerIdTextBox.Size = new Size(500, 30);
        this.customerIdTextBox.Text =
            "Enter a valid Northwind CustomerID, for example: ALFKI," +
            " then RETURN or click outside the TextBox";
        this.customerIdTextBox.Leave +=
            new EventHandler(customerIdTextBox_Leave);
        this.customerIdTextBox.KeyDown +=
            new KeyEventHandler(customerIdTextBox_KeyDown);
        this.Controls.Add(this.customerIdTextBox);
       
        // Set up the DataGridView.
        customersDataGridView.Dock = DockStyle.Top;
        this.Controls.Add(customersDataGridView);

        // Set up the form.
        this.Size = new Size(800, 500);
        this.Load += new EventHandler(Form1_Load);
    }

    // This event handler binds the BindingSource to the DataGridView
    // control's DataSource property.
    private void Form1_Load(
        System.Object sender,
        System.EventArgs e)
    {
        // Attach the BindingSource to the DataGridView.
        this.customersDataGridView.DataSource =
            this.ordersBindingSource;
    }

    // This is a static factory method. It queries the Northwind 
    // database for the orders belonging to the specified
    // customer and returns an IEnumerable.
    public static IEnumerable GetOrdersByCustomerId(string id)
    {
        // Open a connection to the database.
        string connectString = "Integrated Security=SSPI;" +
            "Persist Security Info=False;Initial Catalog=Northwind;" +
            "Data Source= localhost";
        SqlConnection connection = new SqlConnection();
       
        connection.ConnectionString = connectString;
        connection.Open();

        // Execute the query.
        string queryString =
            String.Format("Select * From Orders where CustomerID = '{0}'",
            id);
        SqlCommand command = new SqlCommand(queryString, connection);
        SqlDataReader reader =
            command.ExecuteReader(CommandBehavior.CloseConnection);
        return reader;
               
    }

    // These event handlers are called when the user tabs or clicks
    // out of the customerIdTextBox or hits the return key.
    // The database is then queried with the CustomerID
    //  in the customerIdTextBox.Text property.
    void customerIdTextBox_Leave(object sender, EventArgs e)
    {
        // Attach the data source to the BindingSource control.
        this.ordersBindingSource.DataSource =
            GetOrdersByCustomerId(this.customerIdTextBox.Text);
    }

    void customerIdTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Return)
        {
            // Attach the data source to the BindingSource control.
            this.ordersBindingSource.DataSource =
                GetOrdersByCustomerId(this.customerIdTextBox.Text);
        }
    }

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

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

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

  • ссылки на сборки 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