0

When I add a record to my database, I retrieve the auto generated ID key from the table. I need to place the ID into the Textbox to use later on in my code. Here is my code and it is giving me this error:

Input string was not in a correct format

Here is my code:

// Insert the record by executing the command
numRowsAdded = command.ExecuteNonQuery();

// Use @@IDENTITY to work out the primary key of 
// the new row and display it
command.CommandText = "SELECT @@IDENTITY";
id = Convert.ToInt32(command.ExecuteScalar());

id = Convert.ToInt32(lessonIDTextbox.Text);

2 Answers 2

2

Don't place it in a text box if the only reason you are doing it is to use later in code.

You are getting the error above because lessonIDTextbox does not have a value in it (based on the code you have shown us). id already has a value and you can use it later on in your code. If you are trying to preserve that value across postbacks or something then you might need to explore other options.

If there is some other reason you need to put it in a text box this is the way you would do it:

lessonIDTextbox.Text=id.ToString();
Sign up to request clarification or add additional context in comments.

Comments

0
lessonIDTextbox.Text=command.ExecuteScalar().ToString()

Comments

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.