I have an application where I need to get a certain number as a reference value to send to PLC. To do that I get all the rows from the database and list them on my datagridview (dgv) and with a timer I reload the datagridview with updated rows. To load the data I use the code below;
public void updatedgv()
{
try
{
using (SqlConnection con = new SqlConnection(Program.sqlcon))
{
string q = "SELECT CONCAT(RL.istekID,'-',RL.lineID) '#',M.makName 'Makine Adı',R.partiNo 'PartiNo',C.kimAd 'Kimyasal',RL.miktar 'Miktar',RL.durum 'Durum', RL.lineID 'Kuyruk No' FROM RECLN RL JOIN REC R ON RL.istekID=R.istekID JOIN MAK M ON R.makID=M.makID JOIN CHEM C ON C.kimID=RL.kimID WHERE RL.durum IN (1,2)";
using (SqlCommand com = new SqlCommand(q, con))
{
if (con.State == ConnectionState.Closed) { con.Open(); } else { con.Close(); con.Open(); }
using (SqlDataAdapter sda = new SqlDataAdapter(com))
{
try
{
dt = new DataTable();
sda.Fill(dt);
dgv.DataSource = dt;
}
catch (Exception ex) { this.Text = ex.Message; }
}
}
}
}
catch (Exception ex) { this.Text = ex.Message; }
}
But once in a while, it gives the error below and my application stops working.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I have tried everything to avoid the problem but unfortunately, I couldn't find what I need to do.
I believe I am doing something wrong with my code but I can't figure it out.
You should put more effort into your question, it wastes time of people who could help and makes it difficult to answer, when it's not clear.
I suspect there's couple of things fundamentally wrong with your design.
First of all, if you need only some data from the database, then don't pull all the table to be processed (aka taken one value from it), but rather put the filter into the SQL statement and get one scallar value (or reduced result set, whatever is appropriate).
To answer the question, to avoid the error you get (provided it's from the reading that cell you mentioned, which is actually quite probable), you simply need to ensure you're reading existing cell and existing value:
if (dgv.Rows.Count > 0) // check row exists, to work with a row
{
DataGridViewRow irow = dgv.Rows(0);
if (dgv.Columns.Count > 0) // check column exists, to work with a row
{
// Dim icol As DataGridViewColumn = dgv.Columns(0) ' <<< if column reference needed
DataGridViewCell icell = irow.Cells(0);
if (!IsDBNull(icell) && !IsNothing(icell)) // check cell is not empty
myResult = icell.Value.ToString();// <<< Mind datatypes and type conversions! Not shown here!
}
}
My guess is, that once in a while you get a dbnull
value in that cell and your program crashes.