C#连接数据库及数据绑定
String Constr =@”server=(local)/NetSDK;”+”IntegratedSecurity=SSPI;”+”database=Northwind;”
String SQL=”select * from Employees”;
SqlConnection Conn =new SqlConnection(Constr);
sqlDataAdapter da = new SqlDataAdapter(SQL, Conn );
DataSet ds = new DataSet();
da.fill(ds,”Employees”);
textBox1.DataBindings.Add(“Text”,ds,”Employees.FirstName”);
textBox2.DataBindings.Add(“Text”,ds,”Employees.LastName”);
复杂数据绑定:
如:绑定到dataGrid1控件上:dataGrid1.SetDataBinding(ds,”Employees”);
或:dataGrid1.DataBindings.Add(“DataSource”,ds,”Employees”);
也可写成:
Binding newBind = new Dinding(“Text”,ds,”Employees.FirstName”);
textBox1.DataBindings.Add(newBind);
同步控件与数据源:
先与前面一样,连好数据库,
再从Data选项卡中把DataSet拖到窗体上,并选择第二个单行按钮(Vntyped dataset)
BindingManagerBase bManager;
Form1_load事件:
连接到库……
SqlDataAdapter da = new SqlDataAdapter(SQL, Conn );
da.fill(dataset1,”Employess”);
bManager = this.BindingContext[dataSet1,”Employess”];
Next按钮,作用:显示下一条记录
bManager.position +=1;
back按钮:
mManager.position -=1;
绑定到数组:
String[] carDetails = new string[]{“Mercedez”,”Black”,”e 320” ,” 1999” ,”$1million”};
textBox1.DataBindings.Add(“Text”,carDetails,null);
若要遍历数组:
BindingManagerBase bManager = this.BindingContext[carDetails,null];
绑定到数据表:添加DataSet,并选择无类型.
da.fill(dataSet1,”Employees”);
DataTable myTable = dataSet1.Tables[“Employees”];
ListBox1.DataSource = myTable;
listBox1.DisplayMember = “FirstName”;
textBox1.DataBindings.Add(“Text”,myTable,”FirstName”);
textBox2.DataBindings.Add(“Text”,myTable,”LastName”);
绑定到数据视图:
da.fill(dataset1,”Employees”);
DataTable myTable = dataset1.Tables[“Employees”];
DataView dv = new DataView(myTable,”Country=’ UK ’”,”FirstName”,DataViewRowstate.CurrentRows);
上面表示从DataTable对象的表中选择住在英国的所有雇员的姓名列。
TextBox1.DataBindings.Add(“Text”,dv,”FirstName”);
TextBox2.DataBindings.Add(“Text”,dv,”LastName”);