I'm trying to make the "Current Count" column of my DataGridView only accept integers. I've had success when I use
int value;
string str = my_datagridview.Rows[1].Cells["Current Count"].Value.ToString();
if (int.TryParse(str, out value))
But I'm sure there must be a way where I don't have to write that code for every individual row. I've tried it with a for loop and it gives me a NullReferenceExeption.
Here's my code (including NullReferenceException for loop):
//'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");
        }
    }
}
 
    