How to bind data to a user control by using Visual C# .NET or Visual C# 2005

Article translations Article translations
Article ID: 327413 - View products that this article applies to.
This article was previously published under Q327413
Expand all | Collapse all

On This Page

SUMMARY

This article discusses how to bind data to a user control that is created by using Microsoft Visual C# .NET or Visual C# 2005. This article includes a code sample that creates a user control by using Visual C# .NET, and then binds data to a property of the user control. After creating the user control, you can define an event in the user control class that will be raised when the value of the property is changed. You can implement data binding in the user control in the following way:
  • Create a user control by inheriting from the System.Windows.Forms.UserControl class.
  • Define a property in the user control class.
  • Define an event in the user control class.
  • Create a Windows application, and then add the user control to the Windows Form.
  • Connect to the database, and then populate the data to a dataset.
  • Bind the property of the user control to a column in the dataset.
  • Raise the event defined in the user control class when the property is changed.

INTRODUCTION

This step-by-step article describes how to bind data to a user control by using Microsoft Visual C# .NET or Visual C# 2005. You can bind any property of the user control to a data source. This article contains a code sample that describes how to define a property in a user control class and then bind the property of the user control to the data. In the sample, if the value of the data-bound property is changed, an event that is defined in the user control class is raised.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft SQL Server
  • Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
  • Microsoft .NET Framework
This article assumes that you are familiar with the following topics:
  • Visual C# .NET or Visual C# 2005 syntax
  • Windows Forms
  • Database connectivity

Create a Windows application

To create a Windows application by using Visual C# .NET or Visual C# 2005, follow these steps:
  1. Start Visual Studio .NET or Visual Studio 2005.
  2. On the File menu, point to New, and then click Project. The New Project dialog box appears.
  3. Under Project Types, click Visual C# Projects, and then click Windows Application under Templates.

    Note In Visual Studio 2005, click Visual C# under Project Types.
  4. In the Name box, type MyApp, and then click OK. By default, a Windows Form that is named Form1 is created.

    Note The code should be changed in Visual Studio 2005. When you create a Windows Forms project, Visual C# adds one form to the project by default. This form is named Form1. The two files that represent the form are named Form1.cs and Form1.designer.cs. You write your code in Form1.cs. The Designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you performed by adding controls. For more information about the Windows Forms Designer in Visual C# 2005, visit the following Microsoft Web site:
    http://msdn2.microsoft.com/en-us/library/ms173077.aspx

Create a user control

Create a user control, add a property to the user control, and then make this property bindable. To make the property bindable, add the following Bindable attribute to the property:
[System.ComponentModel.Bindable(true)]
To do this, follow these steps:
  1. On the File menu, point to Add, and then click New Project. The Add New Project dialog box appears.
  2. Under Project Types, click Visual C# Projects, and then click Windows Control Library under Templates.

    Note In Visual Studio 2005, click Visual C# under Project Types.
  3. In the Name box, type MyControl, and then click OK. The UserControl1 control is created.
  4. Add a TextBox control to the UserControl1 control. The textBox1 TextBox control is added.
  5. Add a Label control to the UserControl1 control. The label1 Label control is added.
  6. Put the label1 control above the textBox1 control.
  7. Right-click label1, and then click Properties.
  8. In the Properties pane, set the Text property to Employee Last Name.
  9. In Solution Explorer, right-click UserControl1.cs, and then click View Code.
  10. Add the following code at the end of the UserControl1 class:
    public event System.ComponentModel.PropertyChangedEventHandler employeeNameChanged;
    public string empLName="";
    
    //Makes this property bindable.
    [System.ComponentModel.Bindable(true)] 
    public string employeeLName
    {
        get
        {
          return empLName;
        }
        set
        {
          empLName=value;
          this.textBox1.Text = empLName.ToString();
        }
    }
    public void OnemployeeNameChanged(System.ComponentModel.PropertyChangedEventArgs e)
    {
        //Raise the employeeIDChanged event.
        if (employeeNameChanged != null)
           employeeNameChanged(this,e);
    }
  11. In Solution Explorer, right-click MyControl, and then click Build.

Connect to the Northwind database to obtain the data

Connect to the Northwind database by using the Microsoft OLE DB Provider for SQL Server. Use the SqlDataAdapter class to obtain the data from the database, and then use the Fill method of the SqlDataAdapter class to load the data to the dataset. To do this, follow these steps:
  1. In Solution Explorer, right-click Form1.cs, and then click Open.
  2. On the View menu, click Server Explorer.
  3. In Server Explorer, right-click Data Connections, and then click Add Connection. The Data Link Properties dialog box appears.
  4. On the Provider tab, click Microsoft OLE DB Provider for SQL Server in the OLE DB Provider(s) list, and then click Next.
  5. In the Select or enter a server name box, type or select the name of your server.
  6. Click Use Windows NT Integrated security.
  7. Click Test Connection. If the connection succeeds, select the Northwind database in the Select the database on the server box, and then click OK.
  8. In Server Explorer, expand your connection, and then expand Tables.
  9. Drag the Employees table to the Form1 Windows Form. The SqlConnection object that is named sqlConnection1, and the SqlDataAdapter object that is named sqlDataAdapter1 are added to the component tray of the Form1 Windows Form.
  10. Right-click sqlDataAdapter1, and then click Generate Dataset. The Generate Dataset dialog box appears.
  11. Click OK. The DataSet object that is named dataSet11 is added to the component tray of the Form1 Windows Form.

Add the user control to your Windows application and bind the data to the controls

To bind the data to the controls, you must add the Binding object to the ControlBindingsCollection collection. The Binding object creates and then maintains a simple binding between the property value of an object and the property value of the control. You can use the DataBindings property to access the ControlBindingsCollection collection and obtain the data bindings for the control.

To create a Binding object, you must specify the following values:
  • The property of the control that you want to bind the data to. For example, to display data in a TextBox control, you must specify the Text property in the Binding object.
  • The instance of a data source. For example, use the dataset as a data source.
  • The navigation path. The navigation path may be an empty string (""), may be a single property name, or may be a period-delimited hierarchy of names. When you set the navigation path to an empty string, the ToString method is called on the underlying data source object. For example, if you use a dataset as a data source, you can specify TableName.ColumnName as the navigation path.
You can raise an event when the value of the property in the user control class is changed. To raise the event when the property is changed, you must first declare the event in the user control class. After declaring the event, define the event handler for the event, and then raise the event when the value of the property is changed. To do this, follow these steps:
  1. Add a ListBox control to the Form1 Windows Form. The listBox1 ListBox control is added to the Form1 Windows Form.
  2. Right-click listBox1, and then click Properties.
  3. In the Properties pane, set the DataSource property to dataSet11, and then set the DisplayMember property to Employees.FirstName.
  4. Add two Button controls to the Form1 Windows Form. The button1 Button control and the button2 Button control are added to the Form1 Windows Form.
  5. In Visual Studio .NET 2003, click the My User Controls tab in the toolbox, and then double-click UserControl1 to add the user control to the Form1 Windows Form.

    In Visual Studio .NET 2002, double-click UserControl1 in the toolbox to add the user control to the Form1 Windows Form.
  6. In Design view of the Form1 Windows Form, double-click button1, and then add the following code to the button1_Click procedure:
    //Populate rows to the dataset.
    sqlDataAdapter1.Fill(dataSet11);
    			
    //Set employeeLName as the data-bound property, and set dataSet11 as the data source.
    this.userControl11.DataBindings.Add
    (new Binding("employeeLName",dataSet11,"Employees.LastName"));
    
    //Add an event handler for the employeeNameChanged event.
    this.userControl11.employeeNameChanged += 
    new System.ComponentModel.PropertyChangedEventHandler(this.empLNamechanged_handler);					
    button1.Visible=false;
    		
  7. In Design view of Form1, double-click button2, and then add the following code to the button2_Click procedure:
    System.ComponentModel.PropertyChangedEventArgs  ep= 
    new PropertyChangedEventArgs("employeeLName");
    //Change a value in the LastName column
    string LName="Johnson";
    dataSet11.Tables[0].Rows[0][1]=LName;
    this.userControl11.OnemployeeNameChanged(ep);
  8. Add the following code after the button2_Click procedure:
    private void empLNamechanged_handler(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
       MessageBox.Show("The Property "+ e.PropertyName + " changed");				
    }
  9. On the Build menu, click Build Solution.

Verify that your code works

To verify that your code works, follow these steps:
  1. On the Debug menu, click Start.
  2. Click button1. The values in the FirstName column of the Employees table are displayed in the list box.
  3. Click the name of an employee in the list box. You see the corresponding last name of the employee in the text box.
  4. Click button2 to change the value of the employeeLName property of the user control.

REFERENCES

For additional information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
313482 Roadmap for Windows Forms data binding

313590 Roadmap for ADO.NET
For more information, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn.microsoft.com/en-us/library/aa984099.aspx

Properties

Article ID: 327413 - Last Review: December 11, 2006 - Revision: 2.5
APPLIES TO
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# 2005 Express Edition
Keywords: 
kbproperties kbdatabinding kbctrl kbcontrol kbhowtomaster kbhowto KB327413

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com