winform中的数据绑定

1. 简单的数据绑定

例1

复制代码
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString())) 
{  SqlDataAdapter sda = new SqlDataAdapter("Select * From T_Class Where F_Type='Product' order by F_RootID,F_Orders", conn); DataSet Ds = new DataSet(); sda.Fill(Ds, "T_Class"); //使用DataSet绑定时,必须同时指明DateMember this.dataGridView1.DataSource = Ds; this.dataGridView1.DataMember = "T_Class"; //也可以直接用DataTable来绑定 this.dataGridView1.DataSource = Ds.Tables["T_Class"]; 
} 
复制代码

  简单的数据绑定是将用户控件的某一个属性绑定至某一个类型实例上的某一属性

  采用如下形式进行绑定:引用控件.DataBindings.Add("控件属性", 实例对象, "属性名", true); 

 

 例2

  从数据库中把数据读出来放到一个数据集中,比如List<>、DataTable,DataSet,我一般用List<>,
  然后绑定数据源:

IList<student> sList=StudentDB.GetAllList();
DataGridView.DataSource=sList;

 

  如果你没有设置DataGridView的列,它会自动生成所有列。

2. 复杂数据绑定 


  复杂的数据绑定是将一个以列表为基础的用户控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)绑定至一个数据对象的列表。 
  基本上,Windows Forms的复杂数据绑定允许绑定至支持IList接口的数据列表。此外,如果想通过一个BindingSource组件进行绑定,还可以绑定至一个支持IEnumerable接口的数据列表。 
  对于复杂数据绑定,常用的数据源类型有(代码以DataGridView作为示例控件)。

复制代码
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Collections; namespace DataGridViewBindingData 
{ 
public partial class Form1 : Form 
{ 

public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //this.dataGridView1.DataSource = DataBindingByList1(); //this.dataGridView1.DataSource = DataBindingByList2(); //this.dataGridView1.DataSource = DataBindingByDataTable(); this.dataGridView1.DataSource = DataBindingByBindingSource(); } /// <summary> /// IList接口(包括一维数组,ArrayList等) /// </summary> /// <returns></returns> private ArrayList DataBindingByList1() { ArrayList Al = new ArrayList(); Al.Add(new PersonInfo("a","-1")); Al.Add(new PersonInfo("b","-2")); Al.Add(new PersonInfo("c","-3")); return Al; } /// <summary> /// IList接口(包括一维数组,ArrayList等) /// </summary> /// <returns></returns> private ArrayList DataBindingByList2() { ArrayList list = new ArrayList(); for (int i = 0; i < 10; i++) { list.Add(new DictionaryEntry(i.ToString(),i.ToString()+"_List")); } return list; } /// <summary> /// IListSource接口(DataTable、DataSet等) /// </summary> /// <returns></returns> private DataTable DataBindingByDataTable() { DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("Name"); DataColumn dc2 = new DataColumn("Value"); dt.Columns.Add(dc1); dt.Columns.Add(dc2); for (int i = 1; i <= 10; i++) { DataRow dr = dt.NewRow(); dr[0] = i; dr[1] = i.ToString() + "_DataTable"; dt.Rows.Add(dr); } return dt; } /// <summary> /// IBindingListView接口(如BindingSource类) /// </summary> /// <returns></returns> private BindingSource DataBindingByBindingSource() { Dictionary<string, string> dic = new Dictionary<string, string>(); for (int i = 0; i < 10; i++) { dic.Add(i.ToString(),i.ToString()+"_Dictionary"); } return new BindingSource(dic,null);
}
} }
复制代码

  

  上面代码中BindingSource的Datasource是一个结构类型DictionaryEntry,同样的DictionaryEntry并不能直接赋值给Combobox的DataSource,但通过BindingSource仍然可以间接实现。 这是因为: 
  BindingSource可以作为一个强类型的数据源。其数据源的类型通过以下机制之一固定。使用 Add 方法可将某项添加到 BindingSource 组件中。 
  将 DataSource 属性设置为一个列表、单个对象或类型。(这三者并不一定要实现IList或IListSource) 
  这两种机制都创建一个强类型列表。BindingSource 支持由其 DataSource 和 DataMember 属性指示的简单数据绑定和复杂数据绑定。

 

总结:

根据DataSource绑定的对象的不同,可以有一下几种简单的绑定:

复制代码
// DataSet 、DataTable// 方式1
DataSet ds=new DataSet ();
this.dataGridView1.DataSource=ds.Table[0];
this.dataGridView1.DataSource = ds.Tables["表名"];//  方式2
DataTable dt=new DataTable();
this.dataGridView1.DataSource=dt;// DataView
DataView dv = new DataView();
this.dataGridView1.DataSource = dv;// 设置了DataMember
DataSet ds=new DataSet ();
this.dataGridView1.DataSource = ds;
this.dataGridView1.DataMember = "表名";// ArrayList
ArrayList Al = new ArrayList();
this.dataGridView1.DataSource = Al;// dic
Dictionary<string, string> dic = new Dictionary<string, string>();
this.dataGridView1.DataSource = dic;// List<Object>
this.dataGridVi.DataSource = new BindingList<Object>(List<Object>);
复制代码

 

3. 实例

3.1 手动给dataGridView绑定数据源的方法

c#中手动给dataGridView绑定数据源,能够很自由地进行操作,但展示数据并没有C#自动添加数据源那么方便。可有时为了方便操作数据,我们更愿意手动连接数据源,代码如下:

复制代码
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Restaurant.mdb");//建立数据库连接  
cmd = new OleDbCommand("select * from data", conn);//执行数据连接  
DataSet ds = new DataSet();  
OleDbDataAdapter da = new OleDbDataAdapter(cmd);  
da.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];//数据源 this.dataGridView1.AutoGenerateColumns = false;//不自动 conn.Close();//关闭数据库连接
复制代码

说明:

解决DataGridView绑定了数据源无法更新保存当前行的问题

this.dataGridView.currentCell=null;//该行的作用是取消datagridview行的编辑状态  
adapter.Update(userTable);  

3.2 利用泛型集合向DataGridView中添加数据

List<>泛型集合:

复制代码
private void Form1_Load(object sender, EventArgs e)  
{  //使用List<>泛型集合填充DataGridView  List<Student> students = new List<Student>();  Student hat = new Student("Hathaway", "12", "Male");  Student peter = new Student("Peter","14","Male");  Student dell = new Student("Dell","16","Male");  Student anne = new Student("Anne","19","Female");  students.Add(hat);  students.Add(peter);  students.Add(dell);  students.Add(anne);  this.dataGridView1.DataSource = students;  
}
复制代码

Dictionary<>泛型集合

复制代码
private void Form1_Load(object sender, EventArgs e)  
{  //使用Dictionary<>泛型集合填充DataGridView  Dictionary<String, Student> students = new Dictionary<String, Student>();  Student hat = new Student("Hathaway", "12", "Male");  Student peter = new Student("Peter","14","Male");  Student dell = new Student("Dell","16","Male");  Student anne = new Student("Anne","19","Female");  students.Add(hat.StuName,hat);  students.Add(peter.StuName,peter);  students.Add(dell.StuName,dell);  students.Add(anne.StuName,anne);  //在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<>泛型集合的对象  BindingSource bs = new BindingSource();  //将泛型集合对象的值赋给BindingSourc对象的数据源  bs.DataSource = students.Values;  this.dataGridView1.DataSource = bs;  
}
复制代码

3.3 利用SqlDataReader填充DataGridView 

复制代码
//使用SqlDataReader填充DataGridView  
using (SqlCommand command = new SqlCommand("select * from product", DBService.Conn))  
{  SqlDataReader dr = command.ExecuteReader();  BindingSource bs = new BindingSource();  bs.DataSource = dr;  this.dataGridView1.DataSource = bs;  
}
复制代码

3.4 利用SqlDataAdapter对象向DataGridView中添加数据 

using (SqlDataAdapter da = new SqlDataAdapter("select * from Product", DBService.Conn))  
{  DataSet ds = new DataSet();  da.Fill(ds);  this.dataGridView1.DataSource = ds.Tables[0];  
}

 

转载于:https://www.cnblogs.com/lfxiao/p/7422733.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/369545.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

jQuery数据表和Java集成

jQuery DataTables是一个开放源代码插件&#xff0c;用于在浏览器中创建表。 它具有许多功能&#xff0c;例如排序&#xff0c;服务器端处理&#xff0c; JQUERY UI主题滚动。 该插件的下载链接&#xff1a; http://www.datatables.net/download/ 在本演示中&#xff0c;我…

CSS 属性 - 伪类和伪元素的区别

伪元素和伪类之所以这么容易混淆&#xff0c;是因为他们的效果类似而且写法相仿&#xff0c;但实际上 css3 为了区分两者&#xff0c;已经明确规定了伪类用一个冒号来表示&#xff0c;而伪元素则用两个冒号来表示。 :Pseudo-classes ::Pseudo-elements 但因为兼容性的问题&…

class-感知机Perception

1 感知机模型1.1 模型定义2 感知机学习策略2.1 数据的线性可分性2.2 学习策略3 学习算法3.1 算法原始形式3.2 收敛性3 学习算法的对偶形式1 感知机模型 感知机perceptron是二类分类问题的线性分类模型&#xff0c;输入为实例的特征向量&#xff0c;输出为实例的类别&#xff08…

图片资源 php,php URL图片资源传参生成对应尺寸图片

最近项目中需要上传大图&#xff0c;然后不同设备请求不同大小的图片&#xff0c;之前有用过一个通过URL参数来获取不同大小的图片的接口感觉设计方式请不错&#xff0c;于是就百度看看类似是如何实现的&#xff0c;找了几天找个两个功能类似的记录下。1、图片服务器 imagemagi…

Java中的方法调用有多昂贵

我们都去过那儿。 在查看设计不良的代码的同时&#xff0c;听听作者对人们永远不应该牺牲性能而不是设计的解释。 而且&#xff0c;您不能说服作者摆脱其500行方法&#xff0c;因为链接方法调用会破坏性能。 好吧&#xff0c;这可能在1996年左右是正确的。 但是自那时以来&…

UVa-116 Unidirectional TSP 单向旅行商

题目 https://vjudge.net/problem/uva-116 分析 设d[i][j]为从(i,j)到最后一列的最小开销&#xff0c;则d[i][j]a[i][j]max(d[i1][j1],d[i-1][j1]) 参考数字三角形,用逆推的方法,先确定最后一列d[i][n-1]a[i][n-1],再确定n-2列,此时d[i][n-2] a[i][n-2]min(d[i][n-1],d[i-1][n…

1.HTML

HTML简介 hyper text markup language 即超文本标记语言。 超文本: 就是指页面内可以包含图片、链接&#xff0c;甚至音乐、程序等非文字元素。 标准模板 <!DOCTYPE html> <html lang"en"><head> <meta charset"U…

error connection reset by peer 104

connection reset by peer的常见原因 1.服务器的并发连接数超过了其承载量&#xff0c;服务器会将其中一些连接关闭&#xff1b;2. errno 104错误表明你在对一个对端socket已经关闭的的连接调用write或send方法&#xff0c;在这种情况下&#xff0c;调用write或send方法后&…

php记住表单数据cookie,【PHP基础】cookies和session

1.Cookiescookie 常用于识别用户。cookie 是服务器留在用户计算机中的小文件。每当相同的计算机通过浏览器请求页面时&#xff0c;它同时会发送 cookie。通过 PHP&#xff0c;您能够创建并取回 cookie 的值。1.1、如何创建 cookie&#xff1f;setcookie() 函数用于设置 cookie。…

自己构建GlassFish 4.0快照

这篇文章是关于自己发布GlassFish 4.0快照的&#xff0c;其中包括一些黑客。 我找到了GlassFish FullBuild的官方说明&#xff0c;然后决定自己构建服务器。 有时&#xff0c;您可能不想等待团队升级GlassFish构建文件。 在本条目中&#xff0c;我将Artifactory称为私有Maven存…

【转】utf-8的中文是一个汉字占三个字节长度

因为看到百度里面这个人回答比较生动&#xff0c;印象比较深刻&#xff0c;所以转过来做个笔记 原文链接 https://zhidao.baidu.com/question/1047887004693001899.html 知乎也有更清晰解答 https://www.zhihu.com/question/23374078 1、美国人首先对其英文字符进行了编码&am…

matlab升压斩波仿真,升压斩波电路设计与仿真.doc

升压斩波电路设计与仿真1.序言近年来&#xff0c;不断进步的计算机技术为现代控制技术在实际生产、生活中提供了强有力的技术支持&#xff0c;新的材料和结构器件又促进了电力电子技术的飞速发展&#xff0c;且在各行业中得到广泛的应用。电力电子技术(Power Electronics Techn…

Python selenium web UI之Chrome 与 Chromedriver对应版本映射表及下载地址和配置(windows, Mac OS)...

浏览器及驱动下载 进行web UI 自动化时&#xff0c;需要安装浏览器驱动webdriver&#xff0c;Chrome浏览器需要安装chromedriver.exe 驱动&#xff0c;Firefox需安装 geckodriver.exe 驱动。 Chrome 下载&#xff1a; http://www.slimjet.com/chrome/google-chrome-old-version…

先进的ListenableFuture功能

上次我们熟悉了ListenableFuture 。 我答应介绍更高级的技术&#xff0c;即转换和链接。 让我们从简单的事情开始。 假设我们有从某些异步服务获得的ListenableFuture<String> 。 我们还有一个简单的方法&#xff1a; Document parse(String xml) {//...我们不需要Strin…

修改内表数据并输出结果

*定义结构ty_salesTYPES:BEGIN OF ty_sales, customerid(3) TYPE n, productid(3) TYPE n, orderid(3) TYPE n, customername(10) TYPE c, amount TYPE i, END OF ty_sales.*定义内表和工作区DATA: it_sales TYPE STANDARD TABLE OF ty_sales WITH KEY customerid …

关于css透明度的问题

先看background和background-color background:可以设置背景颜色&#xff0c;背景图片&#xff0c;还有定位。默认background:no-repeat; background-color:只可以设置背景颜色。默认background:repeat; 设置透明度的方式有两种&#xff1a; 第一种&#xff1a; opacity:0.…

java多字段排序,java8 stream多字段排序的实现

很多情况下sql不好解决的多表查询,临时表分组,排序,尽量用java8新特性stream进行处理使用java8新特性,下面先来点基础的List list; 代表某集合//返回 对象集合以类属性一升序排序list.stream().sorted(Comparator.comparing(类::属性一));//返回 对象集合以类属性一降序排序 注…

C#调用Power Shell 管理Office365 执行脚本时遇到的问题

Power Shell管理Office参考http://www.mamicode.com/info-detail-494553.html C#调用Power Shell 参考 https://www.cnblogs.com/chenkai/archive/2010/11/09/1872471.html string pwd "**********";string userName "**********";StringBuilder ss new…

java.util.concurrent.Future基础

在此&#xff0c;我开始撰写一系列有关编程语言中的未来概念&#xff08;也称为promise或delays &#xff09;的文章&#xff0c;标题为&#xff1a; Back to the Future 。 由于对异步&#xff0c;事件驱动&#xff0c;并行和可伸缩系统的需求不断增长&#xff0c;所以期货是非…

javaweb(三十七)——获得MySQL数据库自动生成的主键

测试脚本如下&#xff1a; 1 create table test1 2 ( 3 id int primary key auto_increment, 4 name varchar(20) 5 ); 测试代码&#xff1a; 1 package me.gacl.demo;2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; …