I started learning about C#
and have become stuck with inserting information from textboxes into an Access
database when a click button is used.
The problem I get is during the adding process. The code executes the Try... Catch
part and then returns an error saying "Microsoft Access Database Engine" and doesn't give any clues.
Here is the code:
namespace WindowsFormsApplication1
{
public partial class FormNewUser : Form
{
public FormNewUser()
{
InitializeComponent();
}
private void BTNSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Copy Cegees\Cegees\Cegees\Login.accdb";
String Username = TEXTNewUser.Text;
String Password = TEXTNewPass.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Login (Username, Password) Values(@Username, @Password)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("@Username", OleDbType.VarChar).Value = Username;
cmd.Parameters.Add("@Password", OleDbType.VarChar).Value = Password;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
Password
is a reserved word. Bracket that field name to avoid confusing the db engine.
INSERT into Login (Username, [Password])