2015-11-06 23 views
2

我一直在努力與一個dataviewgrid控件大約一個星期,現在沒有成功。我試圖完成的是檢查單元[0],1,[2]中的空值,並且不允許用戶離開該行,直到它們滿足不爲空的條件。我已經嘗試了許多不同的事件,從單元驗證到行驗證和行離開,輸入等...我的問題是,如果用戶可以說增加名字,然後離開行,我可以驗證數據沒有輸入到其他兩個領域,我需要。但是,它仍然允許他們在完成輸入之前離開該行。我需要一些關於如何最好的方法來檢查這個並不允許用戶輸入空值的邏輯。這是一個屏幕快照和一些我迄今爲止嘗試過的代碼。數據網格視圖後面的正確邏輯C#

enter image description here

,因爲它是現在有控制是隻讀的,我有一個按鈕,創建一個新的條目。我寧願讓用戶能夠自由編輯,刪除和添加他們認爲合適的條目。

 private void datagridCustomers_RowEnter(object sender, DataGridViewCellEventArgs e) 
    { 

     int lastRow = datagridCustomers.Rows.Count - 1; 

     datagridCustomers.ClearSelection(); 

     if (datagridCustomers.Rows[lastRow].Cells[0].Value == null) 
     { 
      MessageBox.Show("Value can't be null."); 
      datagridCustomers.ClearSelection(); 
      datagridCustomers.Rows[lastRow].Cells[0].Selected = true; 
      datagridCustomers.BeginEdit(true); 
     } 
    } 

回答

1

您可以先處理單元驗證事件,檢查EditedFormattedValue爲每個行的「必需」細胞的做到這一點。 null的單元格將具有的string.Empty

當其中一個指定的單元格爲空時,我們可以設置e.Cancel = true並手動將空單元格設置爲CurrentCell

public void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    if (e.ColumnIndex >= 0 && e.ColumnIndex < 3) 
    { 
     for (int col = 0; col < 3; col++) 
     { 
      if (string.IsNullOrEmpty(this.dataGridView1[col, e.RowIndex].EditedFormattedValue.ToString())) 
      { 
       MessageBox.Show("Value can't be null."); 
       e.Cancel = true; 

       this.dataGridView1.CellValidating -= dataGridView1_CellValidating; 
       this.dataGridView1.CurrentCell = this.dataGridView1[col, e.RowIndex]; 
       this.dataGridView1.BeginEdit(true); 
       this.dataGridView1.CellValidating += dataGridView1_CellValidating; 
       return; 
      } 
     } 
    } 
} 

因爲我們設置e.Cancel = true我們還需要添加下面的方法來跳過此驗證的Form.Closing

protected override void WndProc(ref Message m) 
{ 
    switch (((m.WParam.ToInt64() & 0xffff) & 0xfff0)) 
    { 
     case 0xf060: 
      this.dataGridView1.CausesValidation = false; 
      break; 
    } 

    base.WndProc(ref m); 
} 
+0

從中學到一些不同的東西,這似乎工作的偉大。但是,您能否解釋爲什麼您要從活動中描述並重新訂閱?不知道我明白爲什麼會這樣。 – Timg

+0

@Timg當然。我描述/重新訂閱該事件,因爲該行設置了「CurrentCell」。如果不這樣做,設置當前單元格會調用CellValidating事件,該事件再次找到null單元格,重置CurrentCell並觸發相同的循環 - 以堆棧溢出結束。 – OhBeWise