C# DataGridView绑定数据源的几种常见方式
开始以前,先认识一下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 = ; i < ; 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 = ; i <= ; i++)
{
DataRow dr = dt.NewRow();
dr[] = i;
dr[] = 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 = ; i < ; 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[];//数据源
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", "", "Male");
Student peter = new Student("Peter","","Male");
Student dell = new Student("Dell","","Male");
Student anne = new Student("Anne","","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", "", "Male");
Student peter = new Student("Peter","","Male");
Student dell = new Student("Dell","","Male");
Student anne = new Student("Anne","","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[];
}
参考文章
1. 小白,datagridview绑定数据源的几种常见方式。
2. aspnet2005, 在C#中DataGridView控件怎么绑定数据库的数据?
3. officialxiofe, C#中DataGridView控件绑定数据源有几种方式?
4. lllljz, c#中手动给dataGridView绑定数据源的方法.
C# DataGridView绑定数据源的几种常见方式的更多相关文章
- DataGridView绑定数据源的几种方式
使用DataGridView控件,可以显示和编辑来自多种不同类型的数据源的表格数据. 将数据绑定到DataGridView控件非常简单和直观,在大多数情况下,只需设置DataSource属性即可.在绑 ...
- 【转】DataGridView绑定数据源的几种方式
第一种:DataSet ds=new DataSet (); this.dataGridView1.DataSource=ds.Table[0]; 第二种:DataTable dt=new DataT ...
- DataGridView绑定数据源
给DataGridView绑定数据源比較简单,方法主要有两种: 1.直接在控件属性中绑定数据源,这样的方法最简单,但它是直接连接数据库的,这样就和传DataTable的后果差点儿相同了,所以还是尽量避 ...
- 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
适用于app.config与web.config的ConfigUtil读写工具类 之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...
- jedis操作redis的几种常见方式总结
Redis是一个著名的key-value存储系统,也是nosql中的最常见的一种,这篇文章主要给大家总结了关于在java中jedis操作redis的几种常见方式,文中给出了详细的示例代码供大家参考学习 ...
- Tomcat 部署项目的几种常见方式
转自:https://www.cnblogs.com/yuht/p/5714624.html https://www.cnblogs.com/ysocean/p/6893446.html Tomcat ...
- 恶意软件开发——shellcode执行的几种常见方式
一.什么是shellcode? shellcode是一小段代码,用于利用软件漏洞作为有效载荷.它之所以被称为"shellcode",是因为它通常启动一个命令shell,攻击者可以从 ...
- 章鱼哥出品—VB.NET DataGridView绑定数据源 "与货币管理器的位置关联的行不能设置为不可见" 问题的解决
DtaGridView绑定数据源后.假设想让数据条件显示的话,直接使用 My_Row.Visible = False就会出错.错误类型是 "与货币管理器的位置关联的行不能设置为不可见&qu ...
- DataGridView绑定数据源后添加行
本文链接:https://blog.csdn.net/u012386475/article/details/88639799 在已经绑定数据源时,无法以Add的方式方式添加行,会报错 解决方法一: D ...
随机推荐
- OnDrawGizmos函数
如果你想绘制可被点选的gizmos,执行这个函数. 这允许你在场景中快速选择重要的物体. 注意: OnDrawGizmos使用相对鼠标坐标 using UnityEngine; using Syste ...
- EXTJS API
EXTJS API 链接: http://docs.sencha.com/extjs/5.0.0/ http://docs.sencha.com/extjs/4.2.2/ http://docs.se ...
- iOS 基础 第二天(0805)
0805 面向对象三大特性 封装.继承和多态 oc的方法都是在运行过程中才会检测的.编译时方法没实现只会出现警告,运行时出错.如果方法实现了但没有声明,运行时对象仍然可以调用方法不会出错.这是OC中弱 ...
- 【BZOJ 2038】[2009国家集训队]小Z的袜子(hose)
Description HH有一串由各种漂亮的贝壳组成的项链.HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一段贝壳,思考它们所表达的含义.HH不断地收集新的贝壳,因此, 他的项链变 ...
- 5.1:FactoryBean的使用
5.1 FactoryBean的使用 一般情况下,Spring通过反射机制利用bean的class属性指定实现类来实例化bean .在某些情况下,实例化bean过程比较复杂,如果按照传统的方式,则需 ...
- 【莫比乌斯反演】关于Mobius反演与lcm的一些关系与问题简化(BZOJ 2154 crash的数字表格&&BZOJ 2693 jzptab)
BZOJ 2154 crash的数字表格 Description 今天的数学课上,Crash小朋友学习了最小公倍数(Least Common Multiple).对于两个正整数a和b,LCM(a, b ...
- UOJ Round #8 赴京赶考 解题报告
算法零 $n,m \le 100, q \le 10$ 的话,直接给网格中的每一个格点都建一个点,然后该怎么最短路就怎么最短路,该怎么并查集+BFS就怎么并查集+BFS. 复杂度 $O(qnm)$,可 ...
- hdu 1024
参考了一下 http://moxi466839201.blog.163.com/blog/static/18003841620110220374942/ 滚动数组 状态转移方程不太好理解 .... ...
- 关于Spark中RDD的设计的一些分析
RDD, Resilient Distributed Dataset,弹性分布式数据集, 是Spark的核心概念. 对于RDD的原理性的知识,可以参阅Resilient Distributed Dat ...
- onClick(View) of type new View.OnClickListener(){} must override a superclass method
原地址:http://blog.csdn.net/aeolus1019/article/details/8014798 Android开发过程中代码错误报错如下: - implements andro ...