我在Visual Studio 2012中創建了一個Web表單,並且正在製作一個用戶管理表單,以便管理員可以登錄並轉到此頁面並編輯,刪除或添加用戶。我使用MS Access 2013,而且我習慣於在VS 2008中工作。這個完全相同的代碼在VS 2008中與Access 2013一起工作。在窗體上,我有一個綁定到Access中的表格的Gridview。由於某種原因,在調用我的數據圖層類中的函數的按鈕Click
中的if()
語句不斷返回false
,所以我的結果標籤一直說用戶尚未添加到數據庫中。無法從Visual Studio 2012向MS Access 2013中的表添加數據
我試過將值作爲txtUser.Text
傳遞,現在它的寫法是ToString()
。
這裏的按鈕,單擊代碼:
protected void btnAddUser_Click(object sender, EventArgs e)
{
//makes call to saveusers class to add the new user to the database sending the values with it
if (clsDataLayer.SaveUsers(Server.MapPath("~/App_Data/TPSDB.accdb"),
txtUser.Text.ToString(),
txtPassword.Text.ToString()))
{
//if saveusers function is successful and true then informs the user of the results
grdEditManagers.DataBind();
lblResults.Text = "The user has been added to the database!";
}
//if saveusers function is not successful or false then informs user
else
{
lblResults.Text = "The user has not been added to the database!";
}
}
這裏是在clsDataLayer
類SaveUsers()
代碼:
//this function saves the new user
public static bool SaveUsers(string Database, string UserName, string UserPassword)
{
bool recordSaved;
// Creates transaction for rollback in case of error
OleDbTransaction myTransaction = null;
try
{
// creates variable of a new connection to DB
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Database);
conn.Open();//opens connection
OleDbCommand command = conn.CreateCommand();
string strSQL;
// beginning of the commit or rollback transaction
myTransaction = conn.BeginTransaction();
command.Transaction = myTransaction;
//strSQL assigned to first and last names only
strSQL = "Insert into tblManagerLogin " +
"(UserName, Password) values ('" +
UserName + "', '" + UserPassword + "')";
// SQL command for stored procedure
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// statement against connection returns number of rows affected
command.ExecuteNonQuery();
// ends the rollback or commit block
myTransaction.Commit();
// close database connection
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
// rolls back both entries in case an error is caught
myTransaction.Rollback();
recordSaved = false;
}
return recordSaved;
}
以及你吞下異常,你不能說爲什麼recordSaved沒有設置爲true。我也會直接在Access中運行strSQL來檢查這些工作。 – cjb110