c# BindingSource的简单应用

这篇博客介绍了BindingSource在UI和DAL层之间作为数据中间层的作用,展示了如何使用它进行添加、删除、排序、筛选、移动和修改数据项的操作,并提供了相关代码示例。此外,还涉及到数据绑定到DataGridView控件的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值