关于bindingSource的datasouce和list操作文档
bindingSource.datasouce = 集合列表或者其他对象(以下使用A表示)
gridview.datasource = bindingSource
在给gridview绑定好数据源以后,建议直接操作bindingSource来做一些处理,例如添加、删除等操作(add、romove),这样操作会直接操作bindingSource的list集合,注意:不建议使用bindingSource.datasouce = A 这样重新绑定数据源的操作,因为这样很有可能会出现bindingSource的datasouce里面有数据,但是bindingSource的list没有数据,这时候即时重新刷新,界面上也可能会出现不显示数据的情况,(如果刷新数据无作用的话可以使用bindingSource.Accept()把状态设置为unchange状态)。建议,以后使用bindingSource进行相关操作,不建议使用bindingSource.datasouce=A这样的重新绑定数据源的操作。
public partial class Form1 : Form
{
//注当前DGV已经绑定到 ID 和 Name 列
private BindingSourcesource = new BindingSource();
public Form1()
{
InitializeComponent();
}
//窗体加载
private voidForm1_Load(object sender, EventArgs e)
{
this.source.DataSource= typeof(Custom);
this.dataGridView1.DataSource = this.source;
}
//添加
private voidbutton1_Click(object sender, EventArgs e)
{
this.source.Add(newCustom(1,"A"));
this.source.Add(newCustom(2,"B"));
}
//删除
private voidbutton2_Click(object sender, EventArgs e)
{
this.source.RemoveAt(0);
}
//排序
private voidbutton3_Click(object sender, EventArgs e)
{
//可以看看支不支持排序
// bool dd =source.SupportsSorting;
this.source.Sort ="ID ASC";
this.source.ResetBindings(false);
}
//筛选
private voidbutton4_Click(object sender, EventArgs e)
{
this.source.Filter ="ID = 1";
this.source.ResetBindings(false);
}
//向下移动
private voidbutton5_Click(object sender, EventArgs e)
{
this.source.MoveNext();
MessageBox.Show(this.source.Position.ToString());
}
//向上移动
private voidbutton9_Click(object sender, EventArgs e)
{
this.source.MovePrevious();
MessageBox.Show(this.source.Position.ToString());
}
//获取当前项
private voidbutton6_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 voidbutton7_Click(object sender, EventArgs e)
{
Custom custom =(Custom)this.source.Current;
custom.Name = "修改后的值";
this.source.ResetCurrentItem();
}
//删除当前项
private voidbutton8_Click(object sender, EventArgs e)
{
Custom custom =(Custom)this.source.Current;
this.source.Remove(custom);
}
}
//自定义类 字段必须属性公开化
public class Custom
{
public Custom()
{ }
public Custom(int ID,string Name)
{
this.ID = ID;
this.Name = Name;
}
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}