Winforms Data Binding
Objectives Understand Data Binding Implement the ComboBox control Implement the DataGridView control
Data Binding Data Binding is the process of linking retrieved data to the control, which will display the data Use DataSource property to set the data source that the control is displaying data for
Data Binding Interface controls
Examples
ADO.NET components
Examples
DataTable
Data Binding integrates the two
ComboBox control Use DisplayMember to set which field in data source is displayed in this control Use ValueMember to set which field in data source is used as the actual value for the items in this control
ComboBox control Example: use ComboBox control to display data in Categories table of Northwind database
ComboBox control example string connection = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; SqlConnection cn = new SqlConnection(connection); cn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * from Categories", cn); DataSet ds = new DataSet("Northwind"); da.Fill(ds, "Categories"); cn.Close(); cmbCategories.DisplayMember = "CategoryName"; cmbCategories.ValueMember = "CategoryID"; cmbCategories.DataSource = ds.Tables["Categories"];
DataGridView control Use DataMember property to set the name of the list or table in the data source for which the DataGridView is displaying data
DataGridView control Example: use DataGridView control to display data in Products table of Northwind database
DataGridView control example SqlConnection cn = new SqlConnection(connection); cn.Open(); SqlDataAdapter da = new SqlDataAdapter("Select * from Products", cn); DataSet ds = new DataSet("Northwind"); da.Fill(ds, "Products"); cn.Close(); dgvProducts.AutoGenerateColumns = true; dgvProducts.DataSource = ds; dgvProducts.DataMember = "Products";