2016-01-10 18 views
1

我想讓我的DataGridView的「當前計數」列只接受整數。當我使用如何循環訪問datagridview中的每一行?

int value; 
string str = my_datagridview.Rows[1].Cells["Current Count"].Value.ToString(); 
if (int.TryParse(str, out value)) 

我已經成功,但是我敢肯定,必須有一個辦法,我沒有寫代碼的每一個人行。我試過用for循環,它給了我一個NullReferenceExeption。

這裏是我的代碼(包括NullReferenceException異常for循環):

//'Export data' button 
    void export_button_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < my_datagridview.RowCount; i++) 
     { 

     int value; 
     string str = my_datagridview.Rows[i].Cells["Current Count"].Value.ToString(); 
     if (int.TryParse(str, out value)) 
     { 
      //clears form and ensures new file will have header 
      text_box_export.Text = "Item Code,Item Description,Current Count,On Order\r\n"; 

      //ints for for loops 
      int row_count = my_datagridview.RowCount; 
      int cell_count = my_datagridview.Rows[0].Cells.Count; 

      //captures data for each row 
      for (int row_index = 0; row_index <= row_count - 2; row_index++) 
      { 
       //captures data for each column in each row 
       for (int cell_index = 0; cell_index < cell_count; cell_index++) 
       { 
        //adds data to messagebox in stocklist format & leaves comma off the end of each line 
        if (cell_index <= 2) 
        { 
         text_box_export.Text = text_box_export.Text + my_datagridview.Rows[row_index].Cells[cell_index].Value.ToString() + ","; 
        } 
        else 
        { 
         text_box_export.Text = text_box_export.Text + my_datagridview.Rows[row_index].Cells[cell_index].Value.ToString(); 
        } 
       } 
       text_box_export.Text = text_box_export.Text + "\r\n"; 
      } 
      //writes new data from messagebox over stocklist.csv file 
      System.IO.File.WriteAllText("c:\\Stockfile\\stocklist.csv", text_box_export.Text); 
     } 
     else 
     { 
      MessageBox.Show("Data not saved. Please enter only integers"); 
     } 
    } 
} 
+0

在哪一行NullReference引發異常? – tchelidze

回答

0

如果你的主要目標是

,使我的DataGridView的 「當前計數」 列只接受整數

您可以處理dataGridView1.EditingControl.KeyPress事件並驗證EventHandler method中的輸入。
嘗試以下

private string patternToMatchIntegerValues = @"^\d*$"; 

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    my_datagridview.EditingControl.KeyPress -= EditingControl_KeyPress; 
    my_datagridview.EditingControl.KeyPress += EditingControl_KeyPress; 
} 

private void EditingControl_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar)) 
    { 
    var editingControl = (Control)sender; 

    if (!Regex.IsMatch(editingControl.Text + e.KeyChar, patternToMatchIntegerValues)) 
     // Stop the character from being entered into the control since it is non-numerical. 
     e.Handled = true; 
    } 
} 
相關問題