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

若想将 List<T>做为DataGridView的数据源,而后后续还想继续操做的话,须要将List<T>赋值给BindingList对象,this

而后直接将BindingList赋值给DataGridView.DataSource, 如此直接操做BindingList对象时,DataGridView的结果会动态随之更新。spa

1,绑定code

List<UserClass>  listUserClass = new List<UserClass>();
BindingList   BList<
UserClass> ;
listUserClass
= this.UserMethodInitList(); //初始化

BList = new BindingList<UserClass>( listUserClass);//赋值给BindingList对象,Form全局变量
this.DataGridView1.DataSource = BList; //将DataGridView里的数据源绑定成BindingList

2, 获取当前选定的行orm

//获取行对象后
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,删除行blog

int  pos = this.DataGridView1.CurrentRow.Index; //记位置

this.BList.RemoveAt( pos); //删除行,操做BindingList对象便可更新DataGridview

 5,删除多行it

            //容许删除多行

            DataGridViewSelectedRowCollection rows = this.DataGridView1.SelectedRows;

            foreach (DataGridViewRow row in rows)

            {

                this.BList.RemoveAt(row.Index);

            }

 

6, 返向转换io

BindingList<UserClass> Blist = (BindingList<UserClass>) this.DataGridView1.DataSource;


List<UserClass> list1 = List<UserClass>( Blist);
相关文章
相关标签/搜索