我在 Visual Studio 2012 中制作了一个 Web 表单,并且正在制作一个用户管理表单,以便管理员可以登录并转到此页面并编辑、删除或添加用户。我正在使用 MS Access 2013,我习惯于在 VS 2008 中工作。这个完全相同的代码在 VS 2008 和 Access 2013 中工作。在表单上,我有一个绑定到 Access 表的 Gridview。由于某种原因,在我的数据层类中调用函数if()
的按钮事件中的语句不断返回,所以我的结果标签一直说用户尚未添加到数据库中。 Click
false
我已经尝试将值传递为正确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!";
}
}
这是类SaveUsers()
中的代码clsDataLayer
:
//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;
}