Export (0) Print
Expand All
2 out of 14 rated this helpful - Rate this topic

How to: Bind a Windows Forms Control to a Type 

When you are building controls that interact with data, you will sometimes find it necessary to bind a control to a type, rather than an object. This situation arises especially at design time, when data may not be available, but your data-bound controls still need to display information from a type's public interface. For example, you may want a DataGridView control to label its columns at design time with the member names of a custom type.

You can easily bind a control to a type with the BindingSource control.

Example

The following code example demonstrates how to bind a DataGridView control to a custom type by using a BindingSource control.

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

class Form1 : Form
{
    BindingSource bSource  = new BindingSource();
    DataGridView dgv = new DataGridView();

    public Form1()
    {
        // Bind the BindingSource to the DemoCustomer type.
        bSource.DataSource = typeof(DemoCustomer);

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

        // Bind the DataGridView control to the BindingSource.
        dgv.DataSource = bSource  ;
    }
}

// This simple class is used to demonstrate binding to a type.
public class DemoCustomer
{
    // These fields hold the data that backs the public properties.
    DateTime birthDateValue = DateTime.MinValue;
    Guid idValue = Guid.NewGuid();

    // This is a property that represents a birth date.
    public DateTime BirthDate
    {
        get
        {
            return this.birthDateValue;
        }
        set
        {
            if (value != this.birthDateValue)
            {
                this.birthDateValue = value;
            }
        }
    }

    // This is a property that represents a customer ID.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }
}

Compiling the Code

See Also

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.