Insert database using MS Access in C# - c#

It doesn't have an error, but it has a message box showing Ms Access Database Engine and data not insert to database. Can anyone help me solve the problem??
namespace WindowsFormsApplication1
{
public partial class SignUp : Form
{
public SignUp()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Junz\Documents\Register - Copy.mdb";
conn.Open();
String Username = textBox1.Text;
String Password = textBox2.Text;
String Email = textBox3.Text;
String Address = textBox4.Text;
OleDbCommand cmd = new OleDbCommand("INSERT INTO Register(Username,Password,Email,Address) Values(#Username, #Password,#Email,#Address)");
cmd.Connection = conn;
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Username", OleDbType.VarChar,20).Value = Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar,20).Value = Password;
cmd.Parameters.Add("#Email", OleDbType.VarChar,20).Value = Email;
cmd.Parameters.Add("#Address", OleDbType.VarChar,20).Value = Address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}

ExecuteNonQuery() will return int value representing number of rows updated into Database.
if the returned value is 0 you can Display a Message saying DATA NOT ADDED
Try This: write your try block as below.
try
{
if(cmd.ExecuteNonQuery()>0)
MessageBox.Show("DATA ADDED");
else
MessageBox.Show("DATA NOT ADDED");
conn.Close();
}

how about this hope it helps
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Junz\Documents\Register - Copy.mdb";
conn.Open();
String Username = textBox1.Text;
String Password = textBox2.Text;
String Email = textBox3.Text;
String Address = textBox4.Text;
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Register(Username,Password,Email,Address) Values(#Username, #Password,#Email,#Address)";
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Username", OleDbType.VarChar,20).Value = Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar,20).Value = Password;
cmd.Parameters.Add("#Email", OleDbType.VarChar,20).Value = Email;
cmd.Parameters.Add("#Address", OleDbType.VarChar,20).Value = Address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}

Add this to your catch
catch (OleDbException ex){
MessageBox.Show(ex.Message);
conn.Close();
}
And try to insert again, maybe u can see the exact error now.
Good luck.

Related

Insert and Registration data not show in database table visual studio 2019

I'm making a enrollment system using visual studio 2019 and SQL server management studio 2008.When i tried to click insert button 'Inserted Successfully' and there's no errors.When i tried to click registration button 'Record Updated Successfully' and also there's no errors.But when i opened the database and refresh the database table there's no data in the data table.Any support for this issue much appreciated.
private void button2_Click(object sender, EventArgs e)
{
try
{
//taking data from the GUI
string ID = textBox1.Text;
string RegistrationNumber = textBox1.Text;
string StudentName = textBox2.Text;
string DateOfBirth = dateTimePicker1.Text;
String Age = textBox3.Text;
String Gender;
if (radioButton1.Checked == true)
{
Gender = "Male";
}
else
{
Gender = "Female";
}
string ContactNumber = textBox4.Text;
;
if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "")
{
MessageBox.Show("Complete the Missing Data");
}
else if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Click on the selected item after selecting a course");
}
else
{
string course = (comboBox1.SelectedItem != null) ? comboBox1.SelectedItem.ToString() : "";
MessageBox.Show("Student Inserted Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
connection = new SqlConnection("Data Source=.\\(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
}
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO dbo.Table_1(ID, Registration Number, Student Name, Date of Birth, Age, Gender, Contact Number, Course Enrolled In) VALUES(#ID,#RegistrationNumber,#StudentName,#DateOfBirth,#Age,#Gender,#ContactNumber)", connection);
com.CommandType = CommandType.Text;
com.Connection = con;
com.CommandText = "SELECT * FROM dbo.Table_1 WHERE ID = #ID;";
com.Parameters.AddWithValue("#ID", textBox1.Text);
com.Parameters.AddWithValue("#RegistrationNumber", textBox1.Text);
com.Parameters.AddWithValue("#StudentName", textBox2.Text);
com.Parameters.AddWithValue("#DateOfBirth", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Age", textBox3.Text);
com.Parameters.AddWithValue("#Gender", Gender);
com.Parameters.AddWithValue("#ContactNumber", textBox4.Text);
com.ExecuteNonQuery();
com.ExecuteReader();
com.Dispose();
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
private void button6_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
if (ID == null) ;
if (textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || textBox4.Text=="")
{
MessageBox.Show("Please Enter Missing Details");
}
else
{
MessageBox.Show("Record Updated Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
if(con.State==ConnectionState.Closed)
{
con.Open();
}
String sql = "SELECT COUNT(*) AS [Count] FROM dbo.Table_1 WHERE ID =#ID";
SqlCommand cmd = new SqlCommand(sql, con) ;
cmd.Parameters.AddWithValue("#ID", ID);
int Id;
if (!int.TryParse(textBox1.Text, out Id))
{
// Report problem to your user
return;
}
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
{
}
}
con.Close();
}
Based on my test, I find that you defined the SqlCommand.CommandText two times.
Please try to modify your code to the following.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth
);
Also, please note that we should place the MessageBox.Show after the code com.ExecuteNonQuery();.
Here is a code example you could refer to, based on my test, it works well.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ID = textBox1.Text;
string StudentName = textBox2.Text;
DateTime DateOfBirth = dateTimePicker1.Value;
string constr = "sttr";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth);
command.ExecuteNonQuery();
MessageBox.Show("success inserted");
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
string constr = "str";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) AS [Count] FROM Student WHERE ID =#ID";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
MessageBox.Show("Record Updated Successfully!!");
}
After the below line
com.connection = con;
add below code
com.executenonquery();

How to insert new datagridview row in datagridview and update (automatically) in database?

In this case I display values into datagridview from Projects table which it has only 2 columns:
PROJECT_NAME VARCHAR
ID INT // Which is hidden in datagridview, and as AUTOINCREMENT
I have already done with editing values in this table and it works fine:
private void dataGridView4_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string name_project = dataGridView4.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
string id = dataGridView4.Rows[e.RowIndex].Cells[0].Value.ToString();
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; username = root; password = ");
MySqlCommand cmd = new MySqlCommand("UPDATE projekt1.projects SET PROJECTS_NAME = #PROJECTS_NAME WHERE ID = #ID", connection);
cmd.Parameters.Add("#ID", MySqlDbType.Int64).Value = int.Parse(id);
cmd.Parameters.Add("#PROJECTS_NAME", MySqlDbType.VarChar).Value = name_project;
try
{
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But i have a problem with inserting new row and saving automatically in database.
What i've tried?
1) I've tried with RowValidated Event:
private void dataGridView4_RowValidated(object sender, DataGridViewCellEventArgs e)
{
string name_project = dataGridView4.Rows[e.RowIndex].Cells[1].Value.ToString();
string id = dataGridView4.Rows[e.RowIndex].Cells[0].Value.ToString();
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; username = root; password = ");
MySqlCommand cmd = new MySqlCommand("INSERT INTO projekt1.projects(PROJECT_NAME) VALUES(#NPROJECT_NAME);", connection);
cmd.Parameters.Add("#ID", MySqlDbType.Int64).Value = int.Parse(id);
cmd.Parameters.Add("#PROJECT_NAME", MySqlDbType.VarChar).Value = name_project;
try
{
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("ok");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try
{
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
But it didn't work because of
System.FormatException: "Invalid input string format."
2) I've tried that UserAddedRow event too:
private void dataGridView4_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
string name_project= e.Row.Cells[1].Value.ToString();
int id = (int)Convert.ToInt64(e.Row.Cells[0].Value.ToString());
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; username = root; password = ");
MySqlCommand cmd = new MySqlCommand("INSERT INTO projekt1.projects(PROJECT_NAME) VALUES(#NPROJECT_NAME);", connection);
cmd.Parameters.Add("#ID", MySqlDbType.Int64).Value = id;
cmd.Parameters.Add("#PROJECT_NAME", MySqlDbType.VarChar).Value = name_project;
try
{
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("ok");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
but then have that exception in below:
System.NullReferenceException: The object reference has not been set
to the instance of the object.
System.Windows.Forms.DataGridViewCell.Value.get returned null.”
Then i tried removing 2 lines of code:
int id = (int)Convert.ToInt64(e.Row.Cells[0].Value.ToString());
cmd.Parameters.Add("#ID", MySqlDbType.Int64).Value = id;
And it didn't help.
Can someone please write how to solve it? I've searched something but i don't know how to deal with. Greetings.
You can use ShowNewButtonInHeader property
<Columns>
<dx:GridViewCommandColumn ShowNewButtonInHeader="true </dx:GridViewDataTextColumn>
</Columns>

Microsoft Access Engine

I'm trying to add data from Visual Studio to Access in C#. Every time I click the button to save the data an error message pops up saying "Microsoft Database Engine". I have no clue where the problem is. I pasted the code below:
private void btnsave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\My Monroe\Semester 5\Advanced Programming\Final Project\WindowsFormsApplication1\WindowsFormsApplication1\Final exam .accdb";
string fname = first_NameTextBox.Text;
string lname = last_NameTextBox.Text;
string snum = sSNTextBox.Text;
string city = cityTextBox.Text;
string state = stateTextBox.Text;
string telnum = telephone__TextBox.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Customers(First Name, Last Name, SSN,City,State,Telephone# )" + " values(#fname,#lname,#snum,#city,#state,#telnum)", connect);
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#fname", OleDbType.Char, 20).Value = fname;
cmd.Parameters.Add("#lname", OleDbType.Char, 20).Value = lname;
cmd.Parameters.Add("#snum", OleDbType.Numeric, 20).Value = snum;
cmd.Parameters.Add("#city", OleDbType.Char, 20).Value = city;
cmd.Parameters.Add("#state", OleDbType.Char, 20).Value = state;
cmd.Parameters.Add("#telnum", OleDbType.Numeric, 20).Value = telnum;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
A few things to check. Firstly change the catch to
MessageBox.Show(ex.Message);
This will be much more informative!
Secondly on which line does the error get thrown? Thirdly, please check your connection string. When I attach to access my string is always of the form:
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DBFullPath\DBName.accdb;Jet OLEDB:Engine Type=5;Persist Security Info=False;"
if there is no password or
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DBFullPath\DBName.accdb;Jet OLEDB:Engine Type=5;Jet OLEDB:Database Password = password;"
if there is one.
Finally, do you really have a telephone field as numeric? What happens with numbers that start with 0 or international ones with +?
EDIT
Sorry I think you misunderstood me. What I wanted you to do, was to amend the catch so that it reads (in full):
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}

C# update code for logout using mysql

im doing an update statement where the datetimepicker(logout) will insert into the same row as login but its making another row when i logout here is the link : http://imgur.com/a/rAWhi
ps. the problem here is the logout button is inserting into another row.. but i want to insert it in the same row.
here is my code :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from empinfo where username = '" + label4.Text + "' and IDNUMBER = '" + textBox1.Text + "' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Input your id number");
}
else if (i == 0)
{
MessageBox.Show("Username and IDNUMBER didn't match.", "Log-In Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
updateuser();
login frmm = new login();
frmm.Show();
this.Close();
}
con.Close();
}
public void updateuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmdupdate;
cnn.Open();
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout = #logout";
cmdupdate.CommandText = "Insert into employee (logout) values (#logout)";
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
As #Ben in the comments pointed out, you do not need to use insert and only want update so change your code like this:
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout=#logout";
cmdupdate.CommandText += "WHERE IDNUMBER=#IDNUMBER";
cmdupdate.Parameters.AddWithValue("#IDNUMBER", textBox1.Text.Trim());
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
The Where is to make sure it only updates the IDNUMBER on the textbox.
I think you should create different methods for login and logout like
For LOGIN
public static long id;
public void loginuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "Insert into employee (logout) values (#logout)";
cmd.Parameters.AddWithValue("#login", DateTime.Now);
cmd.ExecuteNonQuery();
id = cmd.LastInsertedId; // it will return the id of last inserted row
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
For LOGOUT
public void logoutuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "update employee set logout = #logout WHERE IDNUMBER=#ID";
cmd.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}

insert into a ms access database

i'm realising a litel program with windows forms c#, that saves data in ms ACCESS database.
i write this code
OleDbConnection connect = new OleDbConnection();
private void button1_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb";
string fname = textBox1.Text;
string lname = textBox2.Text;
connect.Open();
OleDbCommand cmd = new OleDbCommand(" INSERT INTO user ([nom],[prenom]) VALUES (#fname,#lname)",connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("erreur" + ex.Source);
connect.Close();
}
}
else
{
MessageBox.Show("probleme connection");
}
}
and i got this error when executing it
"error in insert methode"
i have not idea the error in insert request. have you an idea
Try this. I added the using-statements and [ ]-brackets to the query string.
string fname = textBox1.Text;
string lname = textBox2.Text;
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb"))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO [user] ([nom],[prenom]) VALUES (#fname,#lname)", conn))
{
try
{
conn.Open();
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
}
catch (Exception ex) { MessageBox.Show("Erreur" + ex.Source); }
finally { if (conn.State == ConnectionState.Open) { conn.Close(); } }
}
The OLE DB .NET Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.So, Try to use ? instead of named parameter. for example.
INSERT INTO [user] ([nom],[prenom]) VALUES (?,?)
comand.Parameters.Add("nom", OleDbType.VarChar).Value = fname;

Categories

Resources