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;
}

- 7,151
- 7
- 49
- 71
1 Answers
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.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;If
dgvSale.Rows
has a length bigger than 20 you would have aIndexOutOfRange
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 ofdgvSale
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++;
}

- 744
- 7
- 24
-
@Bilal Ahmed, One more point adding to this answer, Did you think what's it's going to happen when dog Sale.Rows.Count > 19 ???? – bucyDev Feb 22 '19 at 11:19
-
Thanks. I'll edit my answer – Luchspeter Feb 22 '19 at 11:20
-
In order to give the better answer, could be better use Decimal.TryParse(...) instead of decimal.Parse to avoid casting errors. – bucyDev Feb 22 '19 at 11:25
-
Thanks again. Edited my answer – Luchspeter Feb 22 '19 at 11:45