-2

Object reference not set to an instance of an object.

This is the error which i m getting while i trying to delete .. row from my grid view

this is in .. page_ load

gvDetails.DataSource =myBl.DeleteAllCountry(int.Parse(gvDetails.SelectedRow.ToString()));

on data access layer

   public DataTable DeleteCountry(int country_id)
    {
        DataTable dltcontry = new DataTable();
        SqlConnection con = new SqlConnection(@"Data Source=a8-pc\sqlexpress;Integrated Security=True");
        SqlDataAdapter da;
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.connection= con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_DeleteCountry";
            con.Open();
            da = new SqlDataAdapter(cmd);
            cmd.Parameters.AddWithValue("country_id", @country_id);
            cmd.ExecuteNonQuery();
            da.Fill(dltcontry);
            con.Close();
        }

and in business layer the code is like

  public DataTable DeleteAllCountry(int country_id)
  {
     return mydtLayer.DeleteCountry(country_id);
  }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Please format your question properly and use proper english..this is not SMS.. – Asha Jun 11 '13 at 05:21
  • You have stored procedure for delete and you can delete by calling `ExecuteNonQuery` but why you again use same for get data? – Damith Jun 11 '13 at 05:38
  • Please state your question more clearly. This exception looks like a NullPointer-Exception. Usually the debug-output provides a line-number where the exception occurred, including a stack-trace. Use that line-number to investigate the error further. – Alexander Pacha Jun 11 '13 at 05:41

1 Answers1

0

First thing to correct, you need to set connection to your command

cmd.Connection =con;

or in the constructor as below

 SqlCommand command = new SqlCommand(
            queryString, connection);

Another problem is you try to convert selected gvDetails.SelectedRow to int value

check gvDetails.selectedRows.Count before you get value of selected row

if you have selection you can then get cell valu of your country_id column as below

 gvDetails.SelectedRow.cells("country_id").Text

now you can convert this to a int value by using int.TryParse and if it is success send to your BL function to delete the record

Damith
  • 62,401
  • 13
  • 102
  • 153