0
private void btn_Print_Click(object sender, EventArgs e)
{
    CrystalReport1 CR = new CrystalReport1();
    Table[] tab = new Table[20];
    int i = 0;
    foreach (DataGridViewRow row in dgvSale.Rows)
    {
        tab[i].Stock = row.Cells[0].Value.ToString();
        tab[i].Impure = decimal.Parse(row.Cells[1].Value.ToString());
        tab[i].Pure = decimal.Parse(row.Cells[2].Value.ToString());
        tab[i].Labor = int.Parse(row.Cells[3].Value.ToString());
    }
    CR.SetDataSource(tab);
    crystalReportViewer1.ReportSource = CR;     
}
Ashley Medway
  • 7,151
  • 7
  • 49
  • 71

1 Answers1

1
  1. You never initialize your tab Array with entries, which is why you get a NullReferenceException. While objects are not initiliazed or "null" in this case, you cannot access properties and other members from them - because the object simply does not exist yet.

  2. Plus as pointed out in the comments: You could run into problems with your counter. First of all: The way you wrote it (not incrementing i) would not do anything since you would allways edit the 0th element of your array. I would suggest the following;

  3. If dgvSale.Rowshas a length bigger than 20 you would have a IndexOutOfRange exception because you try to edit the 21th element of an array of size 20. So I would initialize the array with the number of rows of dgvSale

  4. Using TryParse instead of Parse increases the stability of your code. (in case that the string value that you want to parse is not parsable into the wanted datatype)

you will have to initialize your array elements before using them:

Table[] tab = new Table[dgvSale.Rows.Count()];
int i = 0;
foreach (DataGridViewRow row in dgvSale.Rows)
{
   tab[i] = new Table(); //Or another valid constructor for this class
   tab[i].Stock = row.Cells[0].Value.ToString();
   tab[i].Impure = Decimal.TryParse(row.Cells[1].Value.ToString(), out decimal value1) ? value1 : 0;
   tab[i].Pure = Decimal.TryParse(row.Cells[2].Value.ToString(), out decimal value2) ? value2 : 0;
   tab[i].Labor = Int.TryParse(row.Cells[3].Value.ToString(), out int value3) ? value3 : 0;
   i++;
}
Luchspeter
  • 744
  • 7
  • 24