datagridview绑定数据源的几种常见方式

合集下载

datagridview用法

datagridview用法

DataGridView用法1.概述D a ta Gr id Vi ew是Wi n do ws Fo rm s中一种常用的控件,用于展示和编辑表格数据。

本文将介绍Da ta Gr id Vi ew的基本用法和常用功能。

2.基本用法2.1创建D a t a G r i d V i e w要使用D at aG ri dVi e w,首先需要在窗体上进行控件的创建和初始化。

可以通过拖拽控件到窗体上或者在代码中动态创建控件。

2.2数据绑定在D at aG ri dV ie w中展示数据通常需要进行数据绑定。

可以通过设置D a ta So ur ce属性来实现数据绑定,可以绑定Da ta Ta bl e、B i nd in gS ou rc e等数据源。

2.3列定义可以通过列定义来指定D at aG ri dV ie w中的列数、列名、列类型等属性。

可以使用Da ta Gr i dV ie w的Co lu mns集合来对列进行操作。

2.4行操作可以通过Da ta Gr idV i ew的R ow s集合对行进行操作,如添加、删除、插入等操作。

可以根据行索引或行对象进行操作。

3.常用功能3.1样式设置可以通过设置Da ta Gr i dV ie w的Ce ll Sty l e、C o lu mn He ad er De fau l tC el lS ty le、R ow H ea de rs De fa ul tCe l lS ty le等属性来设置样式,如背景色、字体、对齐方式等。

3.2单元格编辑D a ta Gr id Vi ew可以方便地对单元格进行编辑,可以根据需要设置单元格的可编辑性,只读属性等。

可以通过事件处理程序来实现特定单元格的编辑操作。

3.3排序和筛选D a ta Gr id Vi ew提供了对数据进行排序和筛选的功能。

可以通过设置A l lo wS or ti ng属性来启用排序功能,通过设置A l lo wU se rT oF il ter C ol um ns属性来启用筛选功能。

NET中DataGridView数据绑定方法详解

NET中DataGridView数据绑定方法详解

NET中DataGridView数据绑定方法详解
1.使用数据集进行数据绑定
-创建一个数据集对象,并指定相应的表结构。

-从数据库中填充数据到数据集中。

- 将DataGridView的数据源属性设置为数据集中的表。

- 设置DataGridView的自动列生成属性为True,以自动生成列。

2.使用数据表进行数据绑定
数据表是数据集中的一种结构,它由行和列组成。

使用数据表进行数据绑定的步骤如下:
-创建一个数据表对象,并定义列名称和类型。

-从数据库中填充数据到数据表中。

- 将DataGridView的数据源属性设置为数据表。

3. 使用BindingSource进行数据绑定
- 创建一个BindingSource对象。

- 设置BindingSource的DataSource属性为数据源。

- 将BindingSource绑定到DataGridView的数据源属性上。

4.使用数据绑定源进行数据绑定
-创建一个数据绑定源对象,并指定相应的数据源。

- 将数据绑定源绑定到DataGridView的数据源属性上。

5.自定义数据绑定
如果以上方法无法满足需求,还可以使用自定义数据绑定方法。

自定义数据绑定通常涉及以下几个方面:
- 创建一个数据源类,实现数据源接口,如IList、IBindingList或ICollectionView。

- 创建一个继承自DataGridView的自定义控件。

C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的⼏种⽅法1.⽤DataSet和DataTable为DataGridView提供数据源String strConn = "Data Source=.;Initial Catalog=His;User ID=sa;Password=*****";SqlConnection conn = new SqlConnection(strConn);String sql= "select * from EMPLOYEE ";conn.Open();SqlCommand cmd = new SqlCommand(sqlId, conn);SqlDataAdapter da = new SqlDataAdapter(cmd);DataSet ds = new DataSet();da.Fill(ds, "EMPLOYEE");dataGridView1.DataSource = ds;this.dataGridView1.AutoGenerateColumns = false;//是否⾃动⽣成列dataGridView1.DataMember = "EMPLOYEE";conn.Close();2.创建DataGridViewRow 对象Add添加⾏String sql_conn= "Data Source=.;Initial Catalog=His;User ID=sa;Password=*****";System.Data.DataTable table =return_table(sql_conn);foreach (System.Data.DataRow date in table.Rows){DataGridViewRow newRow = new DataGridViewRow();newRow.CreateCells(this.dataGridView1);newRow.Cells[0].Value = date[0].ToString();newRow.Cells[1].Value = date[1].ToString();newRow.Cells[2].Value = date[2].ToString();newRow.Cells[3].Value = date[3].ToString();newRow.Cells[4].Value = date[4].ToString();dataGridView1.Rows.Add(newRow);}public System.Data.DataTable return_table(string sql_conn){SqlConnection conn = new SqlConnection(sql_conn);SqlDataReader reader = null;conn.Open();SqlCommand command = new SqlCommand("selectRegID,Name,Area,RoomNO,BedNO from EMPLOYEE", conn);reader = command.ExecuteReader();return ConvertToDataTable(reader);}public DataTable ConvertToDataTable(SqlDataReader dataReader)//SqlDataReader转换为DataTable{DataTable dt = new DataTable();DataTable schemaTable = dataReader.GetSchemaTable();try{//动态构建表,添加列foreach (DataRow dr in schemaTable.Rows){DataColumn dc = new DataColumn();//设置列的数据类型dc.DataType = dr[0].GetType();//设置列的名称dc.ColumnName = dr[0].ToString();//将该列添加进构造的表中dt.Columns.Add(dc);}//读取数据添加进表中while (dataReader.Read()){DataRow row = dt.NewRow();//填充⼀⾏数据for (int i = 0; i < schemaTable.Rows.Count; i++){row[i] = dataReader[i].ToString();}dt.Rows.Add(row);row = null;}dataReader.Close();schemaTable = null;return dt;}catch (Exception ex){//抛出异常throw new Exception(ex.Message); }}。

C#中DataGridView绑定ListT做数据源的操作问题

C#中DataGridView绑定ListT做数据源的操作问题

C#中DataGridView绑定ListT做数据源的操作问题若想将 List<T>作为DataGridView的数据源,然后后续还想继续操作的话,需要将List<T>赋值给BindingList对象,然后直接将BindingList赋值给DataGridView.DataSource, 如此直接操作BindingList对象时,DataGridView的结果会动态随之更新。

1,绑定List<UserClass> listUserClass = new List<UserClass>();BindingList BList<UserClass> ;listUserClass = erMethodInitList(); //初始化BList = new BindingList<UserClass>( listUserClass);//赋值给BindingList对象,Form全局变量this.DataGridView1.DataSource = BList; //将DataGridView⾥的数据源绑定成BindingList2, 获取当前选定的⾏//获取⾏对象后List<UserClass> modiObj = this.DataGridView1.CurrentRow.DataBoundItem as UserClass;3, 修改当前⾏//获取⾏对象后List<UserClass> modiObj = this.DataGridView1.CurrentRow.DataBoundItem as UserClass;modiObj .cost = 10; //修改值int pos = this.DataGridView1.CurrentRow.Index; //记位置this.BList.RemoveAt( pos); //删除⾏this.BList.Insert( pos, modiObj );//添加修改后的⾏到指定位置,不指定位置默认添加到最后4,删除⾏int pos = this.DataGridView1.CurrentRow.Index; //记位置this.BList.RemoveAt( pos); //删除⾏,操作BindingList对象即可更新DataGridview5,删除多⾏//允许删除多⾏DataGridViewSelectedRowCollection rows = this.DataGridView1.SelectedRows;foreach (DataGridViewRow row in rows){this.BList.RemoveAt(row.Index);}6, 返向转换BindingList<UserClass> Blist = (BindingList<UserClass>) this.DataGridView1.DataSource;List<UserClass> list1 = List<UserClass>( Blist);。

DataGridView控件用法(一)绑定数据

DataGridView控件用法(一)绑定数据

DataGridView控件⽤法(⼀)绑定数据⼀、DataGridView控件的⽤法(如何绑定、修改其中某⼀列值、添加序号列、交换任意2列显⽰顺序)1. DataGridView绑定数据源。

在页⾯上拖放⼀个DataGridView控件//连接数据库读取数据,为DataGridView赋值。

String strConn = "server= .\XWPC_DATABASE;uid=数据库⽤户名;pwd=数据库密码;database=数据库名";SqlConnection conn = new SqlConnection(strConn);String sqlId = "select * from [USER] ";conn.Open();SqlCommand cmd = new SqlCommand(sqlId, conn);SqlDataAdapter da = new SqlDataAdapter(cmd);DataSet ds = new DataSet();da.Fill(ds, "USER");DataGridView.DataSource = ds;DataGridView.DataMember = "USER";conn.Close();上述代码执⾏后页⾯上数据显⽰是这样的:2. 修改 DataGridView中数据的表头(本来默认是数据库中的字段名)。

//改变DataGridView的表头DataGridView.Columns[1].HeaderText = "⽤户名";//设置该列宽度DataGridView.Columns[1].Width = 70;3. 将DataGridView最前⾯⼀列编号改为从1开始依次增加的序号(默认的字段编号对⽤户没意义,⽽且不连续)。

//在表前⾯加⼀列表⽰序号DataGridView.Columns[0].HeaderText = "编号";DataGridView.Columns[0].Width = 60;//⾃动整理序列号int coun = DataGridView.RowCount;for (int i = 0; i < coun - 1; i++){DataGridView.Rows[i].Cells[0].Value = i + 1;DataGridView.Rows[i].Cells["USER_ID"].Value = i + 1;}//改变DataGridView的表头DataGridView.Columns[1].HeaderText = "⽤户名";//设置该列宽度DataGridView.Columns[1].Width = 70;DataGridView.Columns[2].HeaderText = "密码";DataGridView.Columns[2].Width = 70;//默认按顺序每列DataGridView依次从ds中对应赋值DataGridView.Columns[0].DataPropertyName = ds.Tables[0].Columns[0].ToString();执⾏后效果如下:4. 对调 DataGridView中某两列的顺序,代码如下: //改变DataGridView的表头DataGridView.Columns[1].HeaderText = "密码";//设置该列宽度DataGridView.Columns[1].Width = 70;DataGridView.Columns[1].DataPropertyName =ds.Tables[0].Columns[2].ToString();DataGridView.Columns[2].HeaderText = "⽤户名";DataGridView.Columns[2].Width =70;DataGridView.Columns[2].DataPropertyName = ds.Tables[0].Columns[1].ToString(); 执⾏效果:5. 设置DataGridView使某列不显⽰、使其不可直接编辑、使其不显⽰最后⼀⾏空⽩。

DataGridViewComboBoxColumn 数据绑定

DataGridViewComboBoxColumn 数据绑定
{
case 0:
Байду номын сангаас j = 1;
break;
case 1:
combox.Items.Add("girl");
4.一般情况下,datagridview只能绑定一个数据源,所以每一行combobox的内容不能随意添加,我们更改了它的这一属性,将弹出这样的对话框:
DataGridViewComboBoxCell value is not valid.
解决方法很简单:在datagridview的事件中添加dataError(),函数体可以为空。
j = 0;
break;
。。。。。
default:
break;
MessageBox.Show(ex.Message);
}
}
【james_hunter】:
因为这些Combobox都是动态创建的,所以可以在创建的时候指定,即GridView的ContentCreat事件里边去,判断当前是不是创建的Combobox,如果是,则强制转换一下,并且指定默认item.
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;
DataGridViewComboBoxColumn comUserName= new DataGridViewComboBoxColumn();
}
dgc.Value = dgc.Items[j];//对单元格进行赋值
}
}
catch (Exception ex)
{
{
dgr = dataGridView1.Rows[i];

在Winform中向DataGridView控件添加数据的三种方式

在Winform中向DataGridView控件添加数据的三种方式

在Winform中向DataGridView控件添加数据的三种方式在Winform中向DataGridView控件添加数据很常用到,现总结3种填充DataGridView方法:1.利用SqlDataAdapter对象向DataGridView中添加数据关键代码:(可以将该代码放到窗体加载事件的方法中)using (SqlDataAdapter da = new SqlDataAdapter("select * from Product", DBService.Conn)){DataSet ds = new DataSet();da.Fill(ds);this.dataGridView1.DataSource = ds.T ables[0];}2. 利用SqlDataReader填充DataGridView关键代码://使用SqlDataReader填充DataGridViewusing (SqlCommand command = new SqlCommand("select * from product", DBService.Conn)){SqlDataReader dr = command.ExecuteReader();BindingSource bs = new BindingSource();bs.DataSource = dr;this.dataGridView1.DataSource = bs;}备注:在很多情况下,BindingSource对象起到一个过渡的作用,因为SqlDataReader对象直接赋给DataGridView时,不能正常显示数据,所以利用BindingSource对象做一个绑定。

3.利用泛型集合向DataGridView中添加数据关键代码:(List<>泛型集合)private void Form1_Load(object sender, EventArgs e){//使用List<>泛型集合填充DataGridViewList<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<>泛型集合,与List<>泛型集合略有不同)private void Form1_Load(object sender, EventArgs e){//使用Dictionary<>泛型集合填充DataGridViewDictionary<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;}★ Writer:cheng ★。

C#DataGridView绑定数据源的几种常见方式

C#DataGridView绑定数据源的几种常见方式

C#DataGridView绑定数据源的⼏种常见⽅式 开始以前,先认识⼀下WinForm控件数据绑定的两种形式,简单数据绑定和复杂数据绑定。

1. 简单的数据绑定例1using (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的列,它会⾃动⽣成所有列。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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

//////////////1)简单数据绑定
//////////////////using (SqlConnection conn = new SqlConnection(Config urationManager.ConnectionStrings["connStr"].ToString()))
//////////////////{
////////////////// SqlDataAdapter sda = new SqlDataAdapter("Select * Fr om 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"]; //////////////////}
//////////////简单的数据绑定是将用户控件的某一个属性绑定至某一个类型实例上的某一属性。

采用如下形式进行绑定:引用控件.DataBin dings.Add("控件属性", 实例对象, "属性名", true);
//////////////2)复杂数据绑定
//////////////复杂的数据绑定是将一个以列表为基础的用户控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)绑定至一个数据对象的列表。

//////////////基本上,Windows Forms的复杂数据绑定允许绑定至支持I List接口的数据列表。

此外,如果想通过一个BindingSource组件进行绑定,还可以绑定至一个支持IEnumerable接口的数据列表。

//////////////对于复杂数据绑定,常用的数据源类型有(代码以DataGri dView作为示例控件):
using System;
using System.Collections.Generic;
using ponentModel;
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并不能直接赋值给Combobo x的DataSource,但通过BindingSource仍然可以间接实现。

////////////////// 这是因为:
//////////////////BindingSource可以作为一个强类型的数据源。

其数据源的类型通过以下机制之一固定:
//////////////////·使用Add 方法可将某项添加到BindingSource 组件中。

//////////////////·将DataSource 属性设置为一个列表、单个对象或类型。

(这三者并不一定要实现IList或IListSource)
//////////////////这两种机制都创建一个强类型列表。

BindingSource 支持由其DataSource 和DataMember 属性指示的简单数据绑定和复杂数据绑定。

相关文档
最新文档