2

I have searched thoroughly, but could not find a way to SET my column data to the variable that I have initialized using a SQL UPDATE statement.

Here is the piece of code that is causing problem:

int maxId;
SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString) ;
SqlCommand dataCommand = new SqlCommand("select max(UserID) from Registration", dataConnection) ;
dataConnection.Open();
maxId = Convert.ToInt32(dataCommand.ExecuteScalar());
string Id = maxId.ToString();

// this next line is not working
SqlCommand _setvin = new SqlCommand("UPDATE Registration SET VIN=maxId , Voted=0  WHERE UserID=maxId", dataConnection);
_setvin.ExecuteNonQuery();

dataConnection.Close();

Please guide me on how I can correct the commented line above.

2 Answers 2

2

Maybe something like this:

SqlCommand _setvin = new SqlCommand("UPDATE Registration SET VIN=@maxId, Voted=0  WHERE UserID=@maxId", dataConnection);
_setvin.Parameters.Add("@maxId", SqlDbType.Int).Value = maxId;
_setvin.ExecuteNonQuery();
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry about that.. Updated the answer
1

I think you're trying to do this:

var _setvin = new SqlCommand("UPDATE Registration SET VIN = @maxId, Voted = 0 WHERE UserID = @maxId", dataConnection);
_setvin.Parameters.AddWithValue("@maxId", maxId);
_setvin.ExecuteNonQuery();

You need to first change your SQL statement to include a parameter for the maxId; I'm calling that @maxId in your SQL. Then you need to supply a value for that parameter to the command. This is done with the Parameters.AddWithValue() method.

4 Comments

with ur solution its giving error "Invalid column name" .. PLEASE NOTE that maxId is the variable name not column name ... **and i want to set the column whose name is VIN with the value contained in maxId **
@Sana I am using @maxId as a variable, not a column. The columns involved here are VIN, Voted, and UserID.
it does not work here ... "invalid column name 'maxId' exception being catched with the solution u jx gave
@Sana Then you're not copying my code correctly, as I don't make any reference to maxId as a column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.