c# BindingSource的简单应用
Posted x1angzeeD.
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# BindingSource的简单应用相关的知识,希望对你有一定的参考价值。
BindingSource充当一个在数据与控件之间的中间层的角色,将数据与控件解耦。
👉关于API介绍可以点击我进行查看👈
简单示例如下:
///*******UI层*******///
//声明BindingSource ,可以给他放到DAL层
//BindingSource可以用作数据容器,即便它没有绑定到数据源上,它内部有一个可以容纳数据的list。
private BindingSource source = new BindingSource();
//添加
private void bnAdd_Click(object sender, EventArgs e)
this.source.Add(new Custom(1, "A"));
this.source.Add(new Custom(2, "B"));
//删除
private void bnDele_Click(object sender, EventArgs e)
this.source.RemoveAt(0);
//排序
private void bnSort_Click(object sender, EventArgs e)
bool wheatherAllowSort = source.SupportsSorting;//可以看看支不支持排序
if (!wheatherAllowSort ) return;
//this.source.Sort = "ID ASC";//列名,后跟“ASC”(升序)或“DESC”(降序)
this.source.Sort = "ID ASC,Name DESC";//先按ID、再按Name排序
this.source.ResetBindings(false);//true 如果数据架构已更改; false 只会更改值
//筛选
private void bnSelc_Click(object sender, EventArgs e)
this.source.Filter = "ID = 1";//用于指定行的筛选方式的字符串,该方法为虚方法可重写
this.source.ResetBindings(false);
//向上移动
private void bnUp_Click(object sender, EventArgs e)
this.source.MovePrevious();
MessageBox.Show(this.source.Position.ToString());//基础列表中当前项的位置
//向下移动
private void bnDown_Click(object sender, EventArgs e)
this.source.MoveNext();
MessageBox.Show(this.source.Position.ToString());
//public void MoveFirst();//移至开头
//public void MoveLast(); //移至末尾
//获取当前项
private void bnCurItem_Click(object sender, EventArgs e)
Custom custom = (Custom)this.source.Current;
MessageBox.Show("所处的位置 : " + this.source.IndexOf(custom).ToString());
MessageBox.Show("custom.Name : " + custom.Name);
//修改当前项
private void bnModify_Click(object sender, EventArgs e)
Custom custom = (Custom)this.source.Current;
custom.Name = "修改后的值";
this.source.ResetCurrentItem();
//删除当前项
private void buDeleCurItem_Click(object sender, EventArgs e)
Custom custom = (Custom)this.source.Current;
this.source.Remove(custom);
private void Form1_Load(object sender, EventArgs e)
this.source.DataSource = typeof(Custom);
this.dataGridView1.DataSource = this.source;
///******DAL层******///
//字段必须属性公开化
public class Custom
public Custom(int ID, string Name)
this.ID = ID;
this.Name = Name;
private string name;
private int id;
public int ID
get return id;
set id = value;
public string Name
get return name;
set name = value;
以上是关于c# BindingSource的简单应用的主要内容,如果未能解决你的问题,请参考以下文章
Form DataGridView绑定BindingSource的几种方式