Search code examples
c#sqlasp.netsql-serverupdatecommand

(Object reference not set to an instance of an object) on updating sql table


I'm trying to update a field in a table of the database when I keep getting the following error

Object reference not set to an instance of an object.

Code:

    public void WILF(string whatIsPlaying)
    {
        using (SqlConnection con = new SqlConnection(conString))
        {
            SqlDataAdapter sda = new SqlDataAdapter("WatchedLast", con);
            sda.SelectCommand.CommandType = CommandType.StoredProcedure;
            sda.SelectCommand.Parameters.AddWithValue("@a", whatIsPlaying);
            sda.SelectCommand.Parameters.AddWithValue("@b", Variables.UserId);
            con.Open();
            sda.UpdateCommand.ExecuteNonQuery();
        }
    }

and here is my store procedure (in case if its needed)

ALTER PROCEDURE WatchedLast

@a nvarchar(30),
@b uniqueidentifier

As

BEGIN
   UPDATE aspnet_Membership
   SET WILO = @a
   WHERE (UserId = @b)
END

I went through step by step debuging to see if the variables (whatIsPlaying and Variables.UserId) are null, but they are not. the values are set in them. I keep getting the error on

sda.UpdateCommand.ExecuteNonQuery(); 

thank you for your help in advance


Solution

  • You're getting the exception because you never specify an UpdateCommand. The constructor for SqlDataAdapter is only setting the SelectCommand.

    Also, I don't see a need for SqlDataAdapter here. I would just use SqlCommand:

    public void WILF(string whatIsPlaying)
    {
        using (SqlConnection con = new SqlConnection(conString))
        {
            con.Open();
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandText = "WatchedLast";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@a", whatIsPlaying);
                cmd.Parameters.AddWithValue("@b", Variables.UserId);
                cmd.ExecuteNonQuery();
            }
        }
    }