我用datagridview绑定了数据表,我打算实现的功能是,如果用户点击了界面右上角的“×”时,提醒用户保存在datagridview中所做的更改。
代码如下:
 在FormCloing事件中, 做如下判断:   
    if (ds.Tables[0].GetChanges() != null)
            { 
         
                if( MessageBox.Show("数据已经更改,是否要保存?", "确认",
                  MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes )
                {
                    saveBT_Click(sender, e);
                }
            
            }
 发现ds.Tables[0].GetChanges() 总是null,数据也就不能保存;如果通过"关闭"按钮,做同样的判断,就可以正常保存。
这是为什么呢?

解决方案 »

  1.   

    你修改了grid上的数据,并没有反映到table上,我想是这个问题,你就做个标记好了,不要这么判断,很容易失误的
      

  2.   

    保存之前必须调用:this.Validate();
      

  3.   

    你点击关闭按钮,默认调用了。点“x”不会,FormCloing()中调用this.Validate();
      

  4.   

    另外通常用DataTable绑定DataGridView的时候,应该将DataTable先赋值给BindingSource控件。然后将
    BindingSource再赋给表格控件,然后保存之前依次调用:
    this.Validate();
    BindingSource.EndEdit();