vadim
vadim

Reputation: 211

ASP.NET Update SQL

I have a SQL Server with a roster/information. I would like to update the table with situps, pushups, and Id. I know how to insert information into a table, but having trouble with the Update part of it.

Here is my code:

SqlConnection conns = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnectionString1"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE test SET SitUps = @SitUps, pushUps = @pushUps WHERE (Id = @Id)", conns);
cmd.CommandType = CommandType.Text;

Label sitL = ((Label)FormView2.FindControl("SitUpsLabel"));
Label pushL = ((Label)FormView2.FindControl("pushUpsLabel"));
Label IdL = ((Label)FormView2.FindControl("IdLabel"));

cmd.Parameters.AddWithValue("@SitUps", sitL.Text);
cmd.Parameters.AddWithValue("@pushUps", pushL.Text);
cmd.Parameters.AddWithValue("@Id", IdL.Text);

I'm getting this error

System.NullReferenceException: Object reference not set to an instance of an object.

I'm pretty sure it's the way I'm treating the Id value. Thanks in advance!!

Upvotes: 1

Views: 256

Answers (3)

Guo Hong Lim
Guo Hong Lim

Reputation: 1710

  1. Ensure that the 3 id that you stated there, "SitUpsLabel", "pushUpsLabel" and "IdLabel" is the same as what you have on the form view.

  2. I noticed that "IdL" color is odd, try using other variable name instead. You could be using "IdL" for some other purposes.

Upvotes: 1

Artur Udod
Artur Udod

Reputation: 4743

The most probable is that FormView2.FindControl returns null, check actual IDs of your controls. How are you sure that exactly this piece of code throws an exception? Seems like you weren't debugging the code (otherwise you would know the exact line and reason), so i advice to do it =)

Upvotes: 1

Waqar Janjua
Waqar Janjua

Reputation: 6123

Before assigning the values to cmd.Parameters first check they are null or not. Example:

if( sitL != null )
{
    cmd.Parameters.AddWithValue("@SitUps", sitL.Text);
}
// In this way add the all parameters.

The error System.NullReferenceException occurs because one of your control was not found and it contains null.

Upvotes: 0

Related Questions