2016-09-19 27 views
6

ném InvalidOperationException khi tôi thay đổi giá trị ô để cập nhật và nhấp trực tiếp vào mục dải menu để mở Biểu tượng mới.Chế độ xem lưới dữ liệu CellValueThay đổi sự kiện ném InvalidOperationException

private void dgv_category_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
     { 
      DataTable dt = new DataTable(); 
      dt = u.operationOnDataBase(sqlquery_selectCategory, 3); 
      if (dt.Rows.Count > 0) 
      { 
       MessageBox.Show("Category Already Exist..."); 

      } 
      else 
      { 
       u.operationOnDataBase(sqlquery_UpdateCategory, 1); 
       u.SyncMaster("update", "CategoryDetails", 0, Convert.ToInt32(dgv_category[1, e.RowIndex].Value.ToString()));//---------Sync 
      } 

      try 
      { 
       dgv_category.DataSource = null; //here Throwing exception 

       u.operationOnDataBase(sqlquery, 3); 
       dgv_category.DataSource = u.dt; 


      } 
      catch (InvalidOperationException) 
      { 
       // exception 
      } 
     } 

Exception- Operation là không hợp lệ vì nó kết quả trong một cuộc gọi reentrant đến chức năng SetCurrentCellAddressCore.

tại System.Windows.Forms.DataGridView.SetCurrentCellAddressCore (Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick) tại System.Windows.Forms.DataGridView.set_CurrentCell (DataGridViewCell giá trị) tại Hệ thống .Windows.Forms.DataGridView.set_DataSource (Object giá trị)

+0

đã u thử mã này 'private void dgv_category_CellEndEdit (object sender, DataGridViewCellEventArgs e) { this.BeginInvoke (MethodInvoker mới (() => } ' –

+0

@GovindTupkar có, tôi đã thử cách này nhưng không hoạt động ... –

+0

Bạn đã thử sự kiện CellLeave hoặc CellValidating? – FakeisMe

Trả lời

0

thay vì đặt DataSource trực tiếp, thiết lập DataSource để một BindingSource, và sau đó thay đổi BindingSource.DataSource?

Ví dụ

//create bindingSource in the WinForms Designer 

Sau đó ...

try 
{ 
    dgv_category.DataSource = null; 
    dgv_category.Rows.Clear(); 
} 
catch{} 
bindingSource.DataSource = ut.dt; 
dgv_category.DataSource = bindingSource; 
bindingSource.ResetBindings(true); 
+0

Tôi đã thử nhưng không làm việc nó ném lỗi trên 'dgv_category.DataSource = null;' –

+0

Đó là lý do tại sao khối try/catch. Đôi khi, bạn có thể gọi DataSource = null và nó sẽ hoạt động tốt, lần khác nó sẽ phát ra lỗi. Việc bắt và bỏ qua những ngoại lệ đó cho phép phần còn lại của mã hoạt động bất kể. –

Các vấn đề liên quan