当我向数据库添加记录时,我从表中检索自动生成的ID密钥。我需要将ID放入文本框中以便稍后在我的代码中使用。这是我的代码,它给了我这个错误:
输入字符串的格式不正确
这是我的代码:
// 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);
答案 0 :(得分:2)
如果您执行此操作的唯一原因是稍后在代码中使用,请不要将其放在文本框中。
您收到上述错误,因为lessonIDTextbox中没有值(基于您向我们展示的代码)。 id
已有值,您可以稍后在代码中使用它。如果您试图在回发或其他内容中保留该值,则可能需要探索其他选项。
如果还有其他原因需要将其放在文本框中,这就是您的方法:
lessonIDTextbox.Text=id.ToString();
答案 1 :(得分:0)
lessonIDTextbox.Text=command.ExecuteScalar().ToString()