2011-04-22 54 views
0

當我將記錄添加到數據庫時,我從表中檢索自動生成的ID密鑰。我需要將ID放入文本框以便稍後在我的代碼中使用。這裏是我的代碼,它是給我這個錯誤:在文本框控件中添加Int值

Input string was not in a correct format

這裏是我的代碼:

// 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

如果唯一的原因,你正在做的,不要把它放在一個文本框它將在代碼中使用。

因爲lessonIDTextbox沒有它的值(根據您向我們顯示的代碼),您正在獲取上述錯誤。 id已經有了一個值,您可以稍後在代碼中使用它。如果您試圖通過回傳或其他方式保留該值,那麼您可能需要探索其他選項。

如果你需要把它放在一個文本框一些這方面的另一個原因是,你會做的方式:

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