让人郁闷的,DatagridView 添加与删除行

让人郁闷的,DatagridView 添加与删除行。

 

不知有没有人用过DatagridView直接添加与删除行,DatagridView上直接添加删除有时会很方便,而且客户也喜欢。使用过InfragisticsUltraGrid的人应该知道,在UltraGrid中删除行和添加行,只需给绑定的集合AddNew方法即可,删除时直接把行设为Delete。而DatagridView却用完全不同的机制。

 

DatagridView上直接调用Rows.Add());,直接添加一行发生导常,使用Row.add(value),也一样不行。

异常:Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

给数据源直接添加行时,界面却一动不动,稳如泰山. 跟踪,发现行集合数,没有随着数据源增加而增加。原来数据源一但给Datagridview后,两都就实现分开管理。

 

 

删除行时也有发生导常:“Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion.”再使用Invalidate方法,界面行数没有变只是多了一行空白。

 

反射一下DataGridView,让我吃了一惊:当数据源不为空时就发生导常,DataSource为空还要添加行干吗?我一度怀疑微软是否支持DataGridView添加与删除。

public virtual int Add()

{

      if (this.DataGridView.DataSource != null)

      {

            throw new InvalidOperationException(SR.GetString("DataGridViewRowCollection_AddUnboundRow"));

      }

      if (this.DataGridView.NoDimensionChangeAllowed)

      {

            throw new InvalidOperationException(SR.GetString("DataGridView_ForbiddenOperationInEventHandler"));

      }

      return this.AddInternal(false, null);

}

 

Google ,找来找去只有msdn2上面几个不痛不养的结果,丝毫解决不了任何问题。看来还是要从DataBinding入手。

添加一个 BindingSource所有的问题都解决了。

 

首先是把数据源设给 BindingSource 的数据源。

然后再把BindingSource设给 DataGridview 的数据源。需要使用BindingSource中转一下才可以。一年多没有使用DataBing了,每天都使用包装好的控件,也不知是好还是坏。

 

之所以写出来,是因为花了我整整一个下午的时候,而网上又找不到相关的资料。能给碰到同样问题的人带来点帮助.

 

posted @ 2006-08-29 09:43  瑞德船长  阅读(25619)  评论(28编辑  收藏  举报