0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CodeMonkey
  • 2,511
  • 4
  • 27
  • 38
  • You may want to take a look at [SqlCommandBuilder](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder(v=vs.110).aspx) class. It will allow you to generate Update and other commands from SelectCommand. – Eugene Podskal Sep 07 '14 at 09:26

1 Answers1

1

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();
        }
    }
}
Zer0
  • 7,191
  • 1
  • 20
  • 34