1

I'm using the code below in order to select the data from a database and bind a datagridview, but I'm having this error and all the questions asked before by other users didn't helped me out.

Code:

        public void popRuta()
    {
        string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=TrafficManager;Integrated Security=True";
        string select = "SELECT ats.NrOrdine, o.Oras as Oras, a.Denumire as Autogara FROM AutogariTrasee ats INNER JOIN Autogari a on a.IDAutogara=ats.IDAutogara INNER JOIN Orase o on o.IDOras=a.IDOras where IDTraseu=@IDTraseu ORDER BY ats.NrOrdine";

       try
        {
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand(select, con);
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("IDTraseu", int.Parse(grdTrasee.CurrentRow.Cells[0].FormattedValue.ToString()));
                SqlDataReader sda = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(sda);
                grdRuta.DataSource = dt;
                grdRuta.Refresh();
                con.Close();
            }   
        }
      catch (Exception er) { MessageBox.Show(er.Message); }

    }

Error:

{"Object reference not set to an instance of an object."}

Can't figure out what am I missing... the c# interface highlights this row when it stops my app: cmd.Parameters.AddWithValue("IDTraseu", int.Parse(grdTrasee.CurrentRow.Cells[0].FormattedValue.ToString()));

cdrrr
  • 147
  • 1
  • 2
  • 10

1 Answers1

3

Since the error is in this line of code:

cmd.Parameters.AddWithValue("IDTraseu", 
int.Parse(grdTrasee.CurrentRow.Cells[0].FormattedValue.ToString()));

The possibilities are the two following:

Either grdTrasee is null or the CurrentRow is null.

Christos
  • 53,228
  • 8
  • 76
  • 108