Steps to Databaind
- Create an empty DataSet instance
- Create a Connection instance
- Specify a SQL statement or Stored Procedure.
- Create a DataAdapter instance from these
- Call its Fill method to pull the data from the database and push into the DataSet.
Simple Data Binding
Each data-bound control in a Windows Forms application maintains a list of bindings for all its data-bound properties. The bindings are in a property named DataBindings, which holds a collection of type ControlBindingCollection. This collection can contain a number of individual control property bindings, with each binding added using the Add method.
Since a text box is capable of displaying on ly one value at a time, you bind its Text property to the FirstName column of the Employees take using the Add method. The Add method has the following parameters:
- The name of the control property to bind to
- The data source
- A string identifying the data source member to bind to
Since we are using a dataset as the data source, the data member is a data column in a data table. In this example, the last parameter is used to bind the Text property to the firstname and the lastname data columns of the employees data table.
Example:
using System.Data.SqlClient;
string connString = @"
server = (local)\netsdk;
integrated security = sspi;
database = northwind
";
string sql = @"
select
*
from
employees
";
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "employees");
// Bind to FirstName column of the Employees table
textBox1.DataBindings.Add("text", ds, "employees.firstname");
// Bind to LastName column of the Employees table
textBox2.DataBindings.Add("text", ds, "employees.lastname");