{“对象引用未设置为对象的实例。”} [复制]

时间:2022-01-28 16:55:26

This question already has an answer here:

这个问题在这里已有答案:

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.

我正在使用下面的代码来从数据库中选择数据并绑定datagridview,但我遇到了这个错误,而其他用户之前提出的所有问题都没有帮助我。

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()));

无法弄清楚我错过了什么...当c#界面停止我的app时突出显示这一行:cmd.Parameters.AddWithValue(“IDTraseu”,int.Parse(grdTrasee.CurrentRow.Cells [0] .FormattedValue.ToString ()));

1 个解决方案

#1


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.

grdTrasee为null或CurrentRow为null。

#1


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.

grdTrasee为null或CurrentRow为null。