DataGridView绑定数据源后动态删除行
两种方法:
(1)数据源使用DataTable
/// <summary> /// 绑定DataGridView /// </summary> private void BindDataGridView() { //绑定DataGridView的数据 string pro_json = client.GetStringAsync($"http://localhost:52972/api/Procuct?ProName={tbKeyword.Text}&ClassID={treeView1.SelectedNode.Name}").Result; //反序列化 DataTable ProList = JsonConvert.DeserializeObject<DataTable>(pro_json); //不自动生成 dataGridView1.AutoGenerateColumns = false; //设置数据源 dataGridView1.DataSource = ProList; }
(2)数据源使用BindingList,因为BindingList实现了IBindingList接口;
相关代码如下:
/// <summary> /// 绑定DataGridView /// </summary> private void BindDataGridView() { //绑定DataGridView的数据 string pro_json = client.GetStringAsync($"http://localhost:52972/api/Procuct?ProName={tbKeyword.Text}&ClassID={treeView1.SelectedNode.Name}").Result; //反序列化 BindingList<ProductModel> ProList = JsonConvert.DeserializeObject<BindingList<ProductModel>>(pro_json); //不自动生成 dataGridView1.AutoGenerateColumns = false; //设置数据源 dataGridView1.DataSource = ProList; }
List和BindingList的转换
DataGridView.DataSource = new BindingList<T>(List<T>);
将绑定BindingList<T>的DataSource转化为List<T>,同理
代码:
List<T> modelList=new List<T>((BindingList<T>)this.DataGridView.DataSource);
说明:BindingList<T>和List<T>都有个构造函数,参数是IEnumerable<T>,既然他们俩个都是继承IEnumerable,当然能相互转换。
下面是这个构造函数的执行过程:
public List(IEnumerable<T> collection) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } ICollection<T> is2 = collection as ICollection<T>; if (is2 != null) { int count = is2.Count; this._items = new T[count]; is2.CopyTo(this._items, 0); this._size = count; } else { this._size = 0; this._items = new T[4]; using (IEnumerator<T> enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) { this.Add(enumerator.Current); } } } }