I cannot access my DB on MS Access when I enter data when I click on save, the MsgBox shows that says that could not find file path directory. Do you know what am I doing wrong and why my DB is not connecting as expected?
public partial class signup : Form
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= amsid.accdb");
OleDbDataAdapter ad = new OleDbDataAdapter();
public signup()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ad.InsertCommand = new OleDbCommand("insert into Signup values(#Username,#Password,#Email,#Admin_Code)", con);
ad.InsertCommand.Parameters.Add("#Username", OleDbType.VarChar).Value = username.Text.ToString();
ad.InsertCommand.Parameters.Add("#Password", OleDbType.VarChar).Value = password.Text.ToString();
ad.InsertCommand.Parameters.Add("#Email", OleDbType.VarChar).Value = email.Text.ToString();
ad.InsertCommand.Parameters.Add("#Admin_Code", OleDbType.VarChar).Value = admincode.Text.ToString();
con.Open();
ad.InsertCommand.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Explicitly state the path of your .accdb file and it should fix your issue.
Related
I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.
I just want to clarify, can i refresh datagridview after insert or update or delete without selecting new sql query again ?
i have googled it, and still have no idea to do it.
here's my code
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
DataTable dtclubroom = new DataTable();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
employee() //<- refresh datagridview
}
Button 4 is to load data, and button 5 inserting data also load data. is there a way refresh datagridview without calling employee() method again ?
You can do it in couple of ways.
Add the newly inserted record to your datatable (you need to use a global datatable variable for this) and refresh your Grid View using this datatable.
You can add the newly inserted record directly to the Grid View
You can follow these techniques also for DELETE and UPDATE
Here is the implementation of idea #1 for your existing code :
DataTable dtclubroom = new DataTable();
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
DataRow dr = dtclubroom.NewRow();
dr["name"] = "Leon";
dr["id"] = "002";
dtclubroom.Rows.Add(dr);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
dataGridView2.DataSource = dtclubroom; //<- refresh datagridview
}
Look that the datatable declaration is moved up and you need to place it in top of your class :
DataTable dtclubroom = new DataTable();
Nothing else need to be global.
I'm new to C#. I trying to develop WPF application. In here when I press Save button I want to refresh the all the text box after insert values to database. How can I do that? Thanks..
addnewcategory.xaml.cs
public addnewcategory()
{
InitializeComponent();
}
private void save_Click(object sender, RoutedEventArgs e)
{
string dbConn = "datasource=localhost;port=3306;username=root";
string Query = "insert into tenderprocess.mstcategory (category) values('" + this.txtcategory.Text + "');";
MySqlConnection mysqlConn = new MySqlConnection(dbConn);
MySqlCommand cmdTenderprocess = new MySqlCommand(Query, mysqlConn);
MySqlDataReader myReader;
try
{
mysqlConn.Open();
myReader = cmdTenderprocess.ExecuteReader();
MessageBox.Show("New Category Successfully Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
In my server windows 2003 the default language and installation is in english language.
Now I need show the GridView of my aspx page in spanish language.
I have tried this code-behind but the output in GridView is always in english and I have error even when I try to run the query strSQL, why?
ExecuteNonQuery requires an open and available Connection.
The connection's current state is closed.
My code below.
I would greatly appreciate any help you can give me in working this problem.
Thank you in advance.
public DataTable GridViewBind()
{
sql = " SELECT * from .... ; ";
try
{
dadapter = new OdbcDataAdapter(sql, conn);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
DataTable dt = dset.Tables[0];
GridView1.DataSource = dt;
string strSQL = " SET lc_time_names = 'es_ES'; ";
OdbcCommand cmd = new OdbcCommand(strSQL, conn);
cmd.ExecuteNonQuery();
GridView1.DataBind();
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dadapter.Dispose();
dadapter = null;
conn.Close();
}
}
protected override void InitializeCulture()
{
Page.Culture = "es-ES";
Page.UICulture = "es-ES";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
InitializeCulture();
GridViewBind();
}
}
EDIT 1
conn.Open();
string strSQL = " SET lc_time_names = 'es_ES'; ";
OdbcCommand cmd = new OdbcCommand(strSQL, conn);
cmd.ExecuteNonQuery();
Make sure you're opening connection before using it in OdbcDataAdapter or OdbcCommand
conn.Open();
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])
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
and doesnt give any clues
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
Don't ignore the exception, it contains information about what went wrong and why.
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.
In your debugger, place a breakpoint inside the catch block and examine the details of the exception. You'll find it contains a lot of information.
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(# "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}