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:

System::Void btnLoad_Click(System::Object^  sender, System::EventArgs^  e)
{
    SqlConnection ^ conDatabase = 
	gcnew SqlConnection(L"Data Source=(local);Database='bcr1';"
			    L"Integrated Security=true");
    SqlCommand    ^ cmdDatabase = 
	gcnew SqlCommand(L"SELECT * FROM dbo.Employees;", conDatabase);

    DataSet ^dsEmployees = gcnew DataSet(L"EmployeesSet");
    SqlDataAdapter ^ sda = gcnew SqlDataAdapter();
    sda->SelectCommand = cmdDatabase;
    sda->Fill(dsEmployees);

    DataRow ^ recEmployee = dsEmployees->Tables[0]->Rows[0];

    txtFirstName->Text = dynamic_cast<String ^>(recEmployee[L"FirstName"]);
    txtLastName->Text = dynamic_cast<String ^>(recEmployee[L"LastName"]);

    conDatabase->Close();
}
 

Home Copyright © 2007-2013, FunctionX