若想將 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);