DataGridView绑定List时无法进行添加删除操作的解决方法

将List<T>转换为BindingList<T>,然后设置DataGridView的DataSource为BindingList<T>!!
代码:

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);
            }

        }

    }

}


posted @ 2008-03-26 06:50 one 阅读(393) 评论(4)  编辑 收藏 所属分类: code

  回复  引用    
#1楼 2008-03-26 08:05 | chao1573> [未注册用户]
datakey?
  回复  引用  查看    
#2楼 2008-06-12 15:36 | ylhyh      
不错,刚好遇到了此问题
  回复  引用    
#3楼 2008-06-15 11:46 | sadfas [未注册用户]
fsadfsadfsdf
  回复  引用    
#4楼 2008-07-03 07:11 | TKer [未注册用户]
有是有了.不过一点的话报错“集合是只读的”.......

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-03-26 15:59 编辑过


相关链接: