Winform項目中TextBox控件DataBindings屬性
DataBindings屬性是很多控件都有的屬性,作用有2方面。一方面是用于與數據庫的數據進行綁定,進行數據顯示。另一方面用于與控件或類的對象進行數據綁定。這里主要關注后者。主要用法是將某個對象的某個屬性與指定對象的指定屬性進行關聯.
Label、TextBox等都包含DataBindings屬性,其類型為ControlBindingsCollection,是Binding類的集合。Binding類代表某對象屬性值和某控件屬性值之間的簡單綁定。如可以將TextBox的Text屬性值綁定到Label的Text屬性值,這樣,當TextBox中的文本被修改的時候,Label的文本也會及時進行修改,如下面的代碼所示:
Label1.DataBindings.Add("Text",TextBox1,"Text");
Binding類除了可以將對象的屬性綁定到控件的屬性之外,還可以將對象列表中當前對象的屬性值綁定到控件的屬性。
當使用Binding的構造函數創(chuàng)建實例時,必須指定三項內容:
- 要綁定到的控件屬性的名稱
- 數據源
- 數據源中解析為列表或屬性的導航路徑
其中,數據源可以為:
- 實現 IBindingList 或 ITypedList 的任何類。包括:DataSet、DataTable、DataView 或 DataViewManager。
- 實現 IList 的任意索引集合類。(必須在創(chuàng)建 Binding 之前創(chuàng)建和填充該集合,并且列表中的所有對象必須為同一類型,否則將引發(fā)異常)
- 強類型對象的強類型 IList。
導航路徑可以為空字符串(默認將調用數據源的ToString()方法)、單個屬性名稱或用點分隔的名稱層次結構。
名稱層次結構是什么意思呢?比如我們有一個Company類,它包含Name屬性和Employees屬性(公司所有Employee的集合),而Employee類又包含Name屬性。那么,如果要將Company的Name屬性綁定到TextBox控件的Text屬性,代碼為:
TextBox1.DataBindings.Add("Text", company, "Name");
如果要綁定Employees的Name屬性,代碼為:
TextBox1.DataBindings.Add("Text", company, "Employees.Name");
Employess.Name即為用點分隔的名稱層次結構。在這里,Employees為一個集合,將Employees.Name綁定到TextBox會出現什么情況呢?測試后可知,TextBox將顯示Employees集合中第一個Employee的Name屬性。
示例:
界面
代碼實現:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DataBindingsDemo { public partial class FrmDataBindings : Form { public FrmDataBindings() { InitializeComponent(); } private void FrmDataBindings_Load(object sender, EventArgs e) { //綁定到DataTable DataTable dtSource = GetDataTable(); this.textBox1.DataBindings.Add("Text", dtSource, "StudentNo"); this.textBox2.DataBindings.Add("Text", dtSource, "StudentName"); this.textBox3.DataBindings.Add("Text", dtSource, "Sex"); //綁定到實體對象 Student stu = new Student() { StudentNo=2,StudentName="測試2",Sex="女"}; //必須是綁定到對象的屬性(此例中綁定到StudentNo,而不是student), this.textBox4.DataBindings.Add("Text", stu, "StudentNo"); this.textBox5.DataBindings.Add("Text", stu, "StudentName"); this.textBox6.DataBindings.Add("Text", stu, "Sex"); } private DataTable GetDataTable() { DataTable dt = new DataTable(); DataColumn dcNo = new DataColumn("StudentNo", typeof(Int32)); DataColumn dcName = new DataColumn("StudentName", typeof(string)); DataColumn dcSex = new DataColumn("Sex", typeof(string)); dt.Columns.Add(dcNo); dt.Columns.Add(dcName); dt.Columns.Add(dcSex); dt.Rows.Add(new object[] { 1,"測試","男"}); return dt; } } public class Student { private int studentNo; public int StudentNo { get { return studentNo; } set { studentNo = value; } } private string studentName; public string StudentName { get { return studentName; } set { studentName = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } } }
運行效果:
到此這篇關于Winform項目中TextBox控件DataBindings屬性的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。