WinForm之之BindingSource基础操作实例教程基础操作实例教程
主要介绍了WinForm之BindingSource基础操作,对BindingSource组建的用法进行较为深入的实例分析,需要的朋
友可以参考下
通常我们在进行数据绑定的时候,常用的数据源有DataSet、DataTable、BindingList<T>、还有强类型数据源。今天我们来通
过实例了解一下BindingSource组建,分享给大家供大家参考借鉴之用。
BindingSource的两个用途:的两个用途:
(1)首先,它提供一个将窗体上的控件绑定到数据的间接层。这是通过将 BindingSource 组件绑定到数据源,然后将窗体上
的控件绑定到 BindingSource 组件来完成的。与数据的所有进一步交互(包括导航、排序、筛选和更新)都是通过调用
BindingSource 组件来完成的。
(2)其次,BindingSource 组件可以充当强类型数据源。使用 Add 方法向 BindingSource 组件添加类型会创建一个该类型的
列表。
一、对一、对BindingSource的基础操作的基础操作——增删改查增删改查
实例代码如下:
public partial class Form1 : Form
{
//注当前DGV已经绑定到 ID 和 Name 列
private BindingSource source = new BindingSource();
public Form1()
{
InitializeComponent();
}
//窗体加载
private void Form1_Load(object sender, EventArgs e)
{
this.source.DataSource = typeof(Custom);
this.dataGridView1.DataSource = this.source;
}
//添加
private void button1_Click(object sender, EventArgs e)
{
this.source.Add(new Custom(1,"A"));
this.source.Add(new Custom(2,"B"));
}
//删除
private void button2_Click(object sender, EventArgs e)
{
this.source.RemoveAt(0);
}
//排序 【有问题】
private void button3_Click(object sender, EventArgs e)
{
this.source.Sort = "ID ASC";
this.source.ResetBindings(false);
}
//筛选 【有问题】
private void button4_Click(object sender, EventArgs e)
{
this.source.Filter = "ID = 1";
this.source.ResetBindings(false);
}
//向下移动
private void button5_Click(object sender, EventArgs e)
{
this.source.MoveNext();
MessageBox.Show(this.source.Position.ToString());
}
//向上移动
private void button9_Click(object sender, EventArgs e)
{
this.source.MovePrevious();
MessageBox.Show(this.source.Position.ToString());
}
//获取当前项
private void button6_Click(object sender, EventArgs e)
{
Custom custom = (Custom)this.source.Current;
MessageBox.Show(" 所处的位置 : " + this.source.IndexOf(custom).ToString());
MessageBox.Show("custom.Name : " + custom.Name);
}
//修改当前项
评论0