I have a serious problem. I have a populated GridView with data from a BD MySql working perfectly.
I also have a button to turn it into a table to be inserted into a PDF using iTextSharp which also works perfectly,
I have a serious problem. I have a populated GridView with data from a BD MySql working perfectly.
I also have a button to turn it into a table to be inserted into a PDF using iTextSharp which also works perfectly,
This exception occurs when you call a method (or, more generally, it references) a null
object. In the case of the line where the error occurs, one of the objects ( tabela
, dataGridView1
, dataGridView1[n, j]
or dataGridView1[n, j].Value
) is null
. You should find out which one it is.
It is almost certain that tabela
is not, otherwise it would never work, whether there is a date filter or not.
dataGridView
, would also have caused problem in the first for
if it was null (since it refers to the collection dataGridView1.Rows
in it.
Since n
and j
are restricted to the limits in dataGridView1.Rows.Count
and dataGridView1.Columns.Count
, respectively, we are not likely to have broken the boundaries of the respective collections. Then it remains for us that the problem must be dataGridView1[n, r].Value
, that is, for some value of n
and r
the result of Value
must be null
.
There are two ways to resolve this problem. The first is using the coalescence operator ??
, like this:
tabela.AddCell(new Phrase((dataGridView1[n, j].Value ?? "").ToString()));
Alternatively, and somewhat more surely, you can (should) replace references to the φ.ToString()
method with calls to the Convert.ToString(φ)
method, which does not work when φ
is null:
tabela.AddCell(new Phrase(Convert.ToString(dataGridView1[n, j].Value)));