Windows Forms數據綁定技術
BindingSource組件是.Net在Windows Forms數據綁定方面最重要的創舉之一,它能夠為窗體封裝數據源,讓控件的數據綁定操作更加簡便。使用時,一般先在窗體上加入一個BindingSource組件,接著將BindingSource組件綁定至數據源,最后再將窗體上的控件綁定至BindingSource組件。通常將BindingNavigator控件與BindingSource組件搭配使用,以便瀏覽BindingSource組件的數據源。
數據綁定的示意圖如圖1所示:
1、數據綁定的具體步驟如下:
(1)設置BindingSource組件的DataMember、DataSource屬性:
- DataSet ds = new DataSet();
- OleDbDataAdapter da= new OleDbDataAdapter(sql,conn);
- da.Fill(ds, "user"); //產生數據源,即DataSet組件
- bdsUser.DataMember = ds.Tables[0].TableName; //bdsUser為BindingSource組件
- bdsUser.DataSource = ds;
(2)控件調用數據綁定方法:
- public Binding Add (
- string propertyName,
- Object dataSource,
- string dataMember
- )
propertyName
要綁定的控件屬性的名稱。
dataSource
表示數據源的 Object。
dataMember
要綁定到的字段名稱。
2、常用控件的數據綁定方法
(1)文本框數據綁定
一般對文本框的Text屬性進行數據綁定,代碼如下:
- txtName.DataBindings.Add("Text", bdsUser, "用戶名");
(2)組合框數據綁定
可分別對組合框的ValueMember、 DisplayMember屬性進行數據綁定:
- cmbPriority.ValueMember = "qx";
- cmbPriority.DisplayMember = "qx";
- cmbPriority.DataSource =bdsQx;
另外,還可對SelectedValue屬性進行數據綁定
- cmbPriority.DataBindings.Add("SelectedValue", bdsUser, "權限");
(3)DataGridView數據綁定
DataGridView控件提供強大、靈活的以表格形式顯示數據的功能。可通過設置DataSource屬性為DataGridView控件綁定數據源:
- dgvUser.DataSource = bdsUser;
BindingNavigator控件是一組用來瀏覽與處理窗體數據源的標準按鈕,包括:第一條、上一條、下一條、最后一條以及數據記錄總數。且BindingNavigator控件繼承了ToolStrip類的所有特性與功能,它同樣扮演了容器的角色,可以包含ToolStripLabel、ToolStripTextBox、ToolStripButton等控件。我們可以在窗體設計階段從下列列表框中選擇要添加至BindingNavigator的ToolStripItem控件,如圖2所示:
使用時,通常將BindingNavigator控件的BindingSource屬性設置成要瀏覽的BindingSource組件,如:
bdnUser.BindingSource = bdsUser;
4、綜合使用上述控件,可以完成一個基本的管理信息系統,程序運行界面如圖3所示:
完整的代碼就不再贅敘,可點擊下載(說明:為簡化代碼,數據庫中未建立權限表)。
原文鏈接:http://www.cnblogs.com/zhouhb/archive/2010/12/19/1910621.html
【編輯推薦】