Home

Control Data Binding

 

Description

When you want to visually deal with records of a database from a Windows application, you may simply want to view the data. Although Microsoft Visual Studio 2005 provides various effective means of binding data to Windows controls, sometimes, you may want to manually bind the controls. To do this, you can use a DataSet object.

The DataSet class allows you to access any type of information from a table. These include table's object name, the columns (and their properties), and the records. This means that you should be able to locate a record, retrieve its value, and assign it to a control. Probably the only real problem is to make sure your DataSet object can get the necessary records. The records could come from a database (Microsoft SQL Server, Oracle, Microsoft Access, Paradox, etc).

Here is an example of binding data to two text boxes to the records of a Microsoft SQL Server table:

private void btnLoad_Click(object sender, EventArgs e)
{
    SqlConnection  conDatabase = 
	new SqlConnection("Data Source=(local);Database='bcr1';" +
			    "Integrated Security=true");
    SqlCommand     cmdDatabase = 
	new SqlCommand("SELECT * FROM dbo.Employees;", conDatabase);

    DataSet dsEmployees = new DataSet("EmployeesSet");
    SqlDataAdapter sda = new SqlDataAdapter();
    sda.SelectCommand = cmdDatabase;
    sda.Fill(dsEmployees);

    DataRow recEmployee = dsEmployees.Tables[0].Rows[0];

    txtFirstName.Text = (String)recEmployee["FirstName"];
    txtLastName.Text = (String)recEmployee["LastName"];

    conDatabase.Close();
}
 

Home Copyright © 2007-2013, FunctionX