Reputation:
I'm creating a database app; with MS Access dataBase file. What happens is everything is inserted correctly, but not Phone Numbers. When entering a Phone Number the Application i am working throws me an exception.
I've double checked my coding and my Database and can't figure out why this issue is caused. Here's the part of the code.
private void btn_Save_Click(object sender, EventArgs e)
{
{
try
{
OleDbCommand DBcmd = new OleDbCommand();
DBcmd.CommandType = CommandType.Text;
DBcmd.CommandText = "INSERT INTO tbl_ClientInfo (FirstName, LastName, Address, ZipCode, City, State, Country, Language, PhoneNr, MobileNr)" + "VALUES (@FirstName, @LastName, @Address, @ZipCode, @City, @State, @Country, @Language, @PhoneNr, @MobileNr)";
DBcmd.Parameters.AddWithValue("@FirstName", txt_FirstName.Text);
DBcmd.Parameters.AddWithValue("@LastName", txt_LastName.Text);
DBcmd.Parameters.AddWithValue("@Address", txt_Address.Text);
DBcmd.Parameters.AddWithValue("@ZipCode", txt_ZipCode.Text);
DBcmd.Parameters.AddWithValue("@City", txt_City.Text);
DBcmd.Parameters.AddWithValue("@State", txt_State.Text);
DBcmd.Parameters.AddWithValue("@Country", ComboBox_Countries.SelectedItem);
DBcmd.Parameters.AddWithValue("@Language", comboBox_Languages.SelectedItem);
DBcmd.Parameters.AddWithValue("@PhoneNr", txt_PhoneNr.Text);
DBcmd.Parameters.AddWithValue("@MobileNr", txt_MobileNr.Text);
DBcmd.Connection = DBconnection;
DBconnection.Open();
DBcmd.ExecuteNonQuery();
DBconnection.Close();
catch (Exception ex)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(@"d:\test.txt");
file.WriteLine(ex);
file.Close();
}
}
}
Thanks in advance
Upvotes: 1
Views: 547
Reputation: 586
You removed the exception you were getting, which was:
System.InvalidOperationException: The connection was not closed. The connection's current state is open
DBconnection is a variable scoped outside of this method, correct? The exception implies that you have already opened this connection someplace else and haven't closed it yet, so you can't open it again. You should either make sure you are closing and disposing of your connection properly every place it is used, or check the state of the connection in the code you posted and don't try to re-open it if it is already open.
Upvotes: 0
Reputation: 216293
LANGUAGE is a reserved keyword in MS-Access Jet. You need to encapsulate it in square brackets
DBcmd.CommandText = "INSERT INTO tbl_ClientInfo (FirstName, LastName, Address, ZipCode, " +
"City, State, Country, [Language], PhoneNr, MobileNr)" +
"VALUES (@FirstName, @LastName, @Address, @ZipCode, " +
"@City, @State, @Country, @Language, @PhoneNr, @MobileNr)";
If it is still possible, I suggest to change that column name. You will always find yourself in this predicament every time you use this table.
Upvotes: 2