2016-06-13 75 views
0
|Column 1|Column 2| 
|1  |1  | 
|2  |2  | 
|3  |3  | 
|4  |4  | 
|5  |5  | 
|6  |6  | 
|7  |7  | 
|8  |8  | 
|9  |9  | 
|  |  | 

比方說,我在我的datagridview顯示此,現在我添加新行(第10行)。我檢查用戶是否在以後使用該數據之前留下任何列,現在如果用戶在列1中插入了某些內容,並且將列2留空,我檢查並顯示他的消息「列2不能爲空」,但是在我希望他的選擇(currentrow)在該空單元格,我的問題是新行沒有索引(它有,但是當我使用它時,我得到錯誤,我不能使用大於最大值的索引行)。我該如何解決它。datagridview新行索引

這是我在哪裏檢查

  int nRows = dataGridView1.Rows.Count; 
      int currColumn = dataGridView1.CurrentCell.ColumnIndex; 
      int currRow = dataGridView1.CurrentCell.RowIndex; 
      string id = dataGridView1.Rows[currRow].Cells[0].Value.ToString(); 
      string opis = dataGridView1.Rows[currRow].Cells[1].Value.ToString(); 

      if (string.IsNullOrEmpty(id)) 
      { 
       MessageBox.Show("Polje broj ne moze biti prazno!"); 
       dataGridView1.CurrentCell = dataGridView1[0, nRows]; 
      } 
      else if (string.IsNullOrEmpty(opis)) 
      { 
       MessageBox.Show("Polje opis ne moze biti prazno!"); 
       dataGridView1.CurrentCell = dataGridView1[1, nRows]; 
      } 
+0

這將是有益的,如果你發佈你所描述的代碼部分代碼。這使得它更容易幫助你 –

+0

我添加後的代碼 – DoLoop

回答

0

一個選項可以訂閱RowsAdded事件的DataGridView

dataGridView.RowsAdded += dataGridView1_RowsAdded 


private void dataGridView1_RowsAdded(object sender, 
    DataGridViewRowsAddedEventArgs e) 
{ 
    // validation code. 
    e.RowIndex; // newly added row index. 
} 
+0

我可以得到與rows.count在cellValueChanged索引,但是當我嘗試在currentCell中使用它,它說 索引超出範圍。必須是非負數且小於集合的大小。 – DoLoop

+0

'rows.Count'返回一個計數,但是你需要的是新添加的行。我在這裏弄錯了嗎? –

+0

嗯,我沒有注意,但現在當我用rowindex獲得索引時,我得到了相同的,但這不是問題。問題是如果我得到索引10,我將currentCell設置爲[1,10](即列2),但由於某種原因它將其設置爲1,9(最後一行但不是新的一行) – DoLoop