How to bind data to a user control by using Visual C# .NET or Visual C# 2005 (327413)
The information in this article applies to:
- Microsoft Visual C# .NET (2003)
- Microsoft Visual C# .NET (2002)
- Microsoft Visual C# 2005, Express Edition
This article was previously published under Q327413 SUMMARYThis 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.
INTRODUCTIONThis 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. back to the topRequirements
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
back to the topCreate a Windows applicationTo create a Windows application by using Visual C# .NET or Visual C# 2005,
follow these steps:
- Start Visual Studio .NET or Visual Studio 2005.
- On the File menu, point to
New, and then click Project. The New
Project dialog box appears.
- 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. - 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: back to the topCreate a user controlCreate 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:
- On the File menu, point to Add, and then click New Project. The Add
New Project dialog box appears.
- 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. - In the Name box, type
MyControl, and then click OK.
The UserControl1 control is created.
- Add a TextBox control to the UserControl1 control. The
textBox1 TextBox control is added.
- Add a Label control to the UserControl1 control. The
label1 Label control is added.
- Put the label1 control above the
textBox1 control.
- Right-click label1, and then click
Properties.
- In the Properties pane, set the
Text property to Employee Last
Name.
- In Solution Explorer, right-click
UserControl1.cs, and then click View
Code.
- 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);
} - In Solution Explorer, right-click
MyControl, and then click Build.
back to the topConnect to the Northwind database to obtain the dataConnect 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:
- In Solution Explorer, right-click
Form1.cs, and then click Open.
- On the View menu, click Server
Explorer.
- In Server Explorer, right-click Data
Connections, and then click Add Connection. The
Data Link Properties dialog box appears.
- On the Provider tab, click
Microsoft OLE DB Provider for SQL Server in the OLE DB
Provider(s) list, and then click Next.
- In the Select or enter a server name box,
type or select the name of your server.
- Click Use Windows NT Integrated security.
- Click Test Connection. If the connection
succeeds, select the Northwind database in the Select
the database on the server box, and then click
OK.
- In Server Explorer, expand your connection, and then expand Tables.
- 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.
- Right-click sqlDataAdapter1, and then
click Generate Dataset. The Generate Dataset
dialog box appears.
- Click OK. The DataSet object that is named
dataSet11 is added to the component tray of
the Form1 Windows Form.
back to the topAdd the user control to your Windows application and bind the data to the controlsTo 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:
- Add a ListBox control to the Form1 Windows Form. The
listBox1 ListBox control is added to the
Form1 Windows Form.
- Right-click listBox1, and then click
Properties.
- In the Properties pane, set the
DataSource property to dataSet11, and then
set the DisplayMember property to
Employees.FirstName.
- 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.
- 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. - 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;
- 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); - 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");
} - On the Build menu, click Build
Solution.
back to the
topVerify that your code worksTo verify that your code works, follow these steps:
- On the Debug menu, click
Start.
- Click button1. The values in
the FirstName column of the Employees table are displayed in the list box.
- Click the name of an employee in the list box. You see the corresponding last name of the employee in the text box.
- Click button2 to change the
value of the employeeLName property of the user control.
back to the
topREFERENCES
For additional information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
313482
Roadmap for Windows Forms data binding
For more information, visit the following
Microsoft Developer Network (MSDN) Web site: back to the
top
Modification Type: | Major | Last Reviewed: | 1/17/2006 |
---|
Keywords: | kbProperties kbDataBinding kbCtrl kbControl kbHOWTOmaster kbhowto KB327413 kbAudDeveloper |
---|
|