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];
}

winform中的数据绑定的更多相关文章

  1. C# WinForm 中ComboBox数据绑定的问题 (转)

    来自:http://blog.sina.com.cn/s/blog_5fb9e26301013wga.html C# WinForm 中ComboBox数据绑定的问题 怎样让WinForm中的Comb ...

  2. WPF入门教程系列十五——WPF中的数据绑定(一)

    使用Windows Presentation Foundation (WPF) 可以很方便的设计出强大的用户界面,同时 WPF提供了数据绑定功能.WPF的数据绑定跟Winform与ASP.NET中的数 ...

  3. [C#]WinForm 中 comboBox控件之数据绑定

    [C#]WinForm 中 comboBox控件之数据绑定 一.IList 现在我们直接创建一个List集合,然后绑定 IList<string> list = new List<s ...

  4. WPF入门教程系列十八——WPF中的数据绑定(四)

    六.排序 如果想以特定的方式对数据进行排序,可以绑定到 CollectionViewSource,而不是直接绑定到 ObjectDataProvider.CollectionViewSource 则会 ...

  5. winform中dataGridView单元格根据值设置新值,彻底解决绑定后数据类型转换的困难

    // winform中dataGridView单元格在数据绑定后,数据类型更改困难,只能迂回实现.有时候需要将数字变换为不同的文字描述,就会出现int32到string类型转换的异常,借助CellFo ...

  6. 【接上一篇】winform中dataGridView高度和宽度自适应填充完数据的高度和宽度,即dataGridView根据数据自适应大小

    上一篇:winform中dataGridView高度自适应填充完数据的高度 winform中dataGridView高度自适应填充完数据的高度,就是dataGridView自身不产生滚动条,自己的高度 ...

  7. winform中dataGridView高度自适应填充完数据的高度

    // winform中dataGridView高度自适应填充完数据的高度,就是dataGridView自身不产生滚动条,自己的高度是根据数据的多少而变动. 在load的时候,数据绑定后,加上如下代码: ...

  8. winform中DataGridView实现分页功能

    WinForm轻松实现自定义分页 (转载) WinForm轻松实现自定义分页 (转载)   转载至http://xuzhihong1987.blog.163.com/blog/static/26731 ...

  9. Winform中实现读取xml配置文件并动态配置ZedGraph的RadioGroup的选项

    场景 Winform中对ZedGraph的RadioGroup进行数据源绑定,即通过代码添加选项: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/ ...

随机推荐

  1. Algorithm --> 求阶乘末尾0的个数

    求阶乘末尾0的个数 (1)给定一个整数N,那么N的阶乘N!末尾有多少个0?比如:N=10,N!=3628800,N!的末尾有2个0. (2)求N!的二进制表示中最低位为1的位置. 第一题 考虑哪些数相 ...

  2. apache实现301永久性重定向代码

    301重定向(301 redirect)又叫301代表永久性转移(Permanently Moved),将各种网络请求重新定个方向转到其它位置,是网页更改地址后对搜索引擎友好的最好方法,只要不是暂时搬 ...

  3. 使用cocopod管理第三方

    扭捏了两年多一直不愿意使用cocopod来管理第三方,一直感觉直接拖拽第三方就挺方便的,直到今天使用第三方库WebViewJavascriptBridge,拖拽一直有问题,不得已研究.使用了cocop ...

  4. 简单谈谈DNS的工作原理及实践

    DNS协议简介 dns(Domain Name System)是一个全球化的分布式数据库系统,用于存储域名和互联网IP地址的映射关系.dns协议是计算机协议栈应用层中,应用最广泛的协议之一.用户每一次 ...

  5. [福大软工] W班 团队第一次作业—团队展示成绩公布

    作业地址 https://edu.cnblogs.com/campus/fzu/FZUSoftwareEngineering1715W/homework/906 作业要求 根据已经组队的队伍组成, 每 ...

  6. Python实现网站模拟登陆

    一.实验简介 1.1 基本介绍 本实验中我们将通过分析登陆流程并使用 Python 实现模拟登陆到一个实验提供的网站,在实验过程中将学习并实践 Python 的网络编程,Python 实现模拟登陆的方 ...

  7. fflush(stdin)与fflush(stdout)

    1.fflush(stdin): 作用:清理标准输入流,把多余的未被保存的数据丢掉.. 如: int main() { int num; char str[10]; cin>>num; c ...

  8. .net 小程序获取用户UnionID

    第一次写博客,写的不好多多海涵! 1.小程序获取UnionID的流程用code去换取session_key,然后去解密小程序获取到的那串字符! 话不多说,原理大家都懂!!!!!! 直接上代码 publ ...

  9. Mongodb 3 查询优化(语句优化、建索引)

    一.explain(),语句分析工具 MongoDB 3.0之后,explain的返回与使用方法与之前版本有了很大的变化,介于3.0之后的优秀特色和我们目前所使用给的是3.0.7版本,本文仅针对Mon ...

  10. Java面试题合集(二)

    接下来几篇文章准备系统整理一下有关Java的面试题,分为基础篇,javaweb篇,框架篇,数据库篇,多线程篇,并发篇,算法篇等等,陆续更新中.其他方面如前端后端等等的面试题也在整理中,都会有的. 注: ...