服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C# DataGridView绑定数据源的方法

C# DataGridView绑定数据源的方法

2022-03-01 14:18五维思考 C#

这篇文章主要为大家详细介绍了C# DataGridView绑定数据源的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

开始以前,先认识一下WinForm控件数据绑定的两种形式,简单数据绑定和复杂数据绑定。

1. 简单的数据绑定

例1

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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<>,

然后绑定数据源:

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

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

2. 复杂数据绑定

复杂的数据绑定是将一个以列表为基础的用户控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)绑定至一个数据对象的列表。

基本上,Windows Forms的复杂数据绑定允许绑定至支持IList接口的数据列表。此外,如果想通过一个BindingSource组件进行绑定,还可以绑定至一个支持IEnumerable接口的数据列表。

对于复杂数据绑定,常用的数据源类型有(代码以DataGridView作为示例控件)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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绑定的对象的不同,可以有一下几种简单的绑定:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 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#自动添加数据源那么方便。可有时为了方便操作数据,我们更愿意手动连接数据源,代码如下:

?
1
2
3
4
5
6
7
8
9
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绑定了数据源无法更新保存当前行的问题

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

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

List<>泛型集合:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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<>泛型集合

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

?
1
2
3
4
5
6
7
8
//使用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中添加数据

?
1
2
3
4
5
6
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/zhaoshujie/p/9679002.html

延伸 · 阅读

精彩推荐
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10