vshost32.exe stops working when connecting to Access database - c#

I'm using Visual Studio 2012 and connecting it to MS Access 2016. My system is working without any error but when I try to click the search button the vshost32.exe always stops working.
Here is my code:
namespace WindowsFormsApplication4
{
public partial class SalesInventory : Form
{
public SalesInventory()
{
InitializeComponent();
}
private void SearchButton_Click(object sender, EventArgs e)
{
string source = #"Provider= Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Irma\\Documents\\project.accbd;Persist Securit Info= False";
OleDbConnection conn = new OleDbConnection(source);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
string str = "Select * FROM Products WHERE Product_Name LIKE '%" + SearchTextBox.Text + "%'";
OleDbDataAdapter da = new OleDbDataAdapter(str, conn);
DataTable ds = new DataTable();
ds.Clear();
da.Fill(ds);
GrindView.DataSource = ds;
conn.Close();
}
else
{
string str = "Select * FROM Products WHERE Product_Name LIKE '%" + SearchTextBox.Text + "%'";
OleDbDataAdapter da = new OleDbDataAdapter(str, conn);
DataTable ds = new DataTable();
ds.Clear();
da.Fill(ds);
GrindView.DataSource = ds;
conn.Close();
}
}
}
}
Even with this code vshost32.exe stops working:
private void AddBut_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider= Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Irma\\Documents\\project.accbd;Persist Security Info= False";
OleDbCommand command = new OleDbCommand("Insert into Product([Product_Name]) VALUES (#ProdName)");
command.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
command.Parameters.AddWithValue("#ProdName", ProdNameText.Text);
try
{
command.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
OleDbCommand cmd = new OleDbCommand("Insert into product_Fields([Product_Name],[Description],[Category],[Quantity],[Price],[Supplier_Name]) VALUES (#prodName,#Description,#Category,#Quantity,#Price,#Supplier_Name)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#prodName", ProdNameText.Text);
cmd.Parameters.AddWithValue("#Description", DescriptionComboBox.Text);
cmd.Parameters.AddWithValue("#Category", CategoryComboBox.Text);
cmd.Parameters.AddWithValue("#Quantity", QuantityBox.Text);
cmd.Parameters.AddWithValue("#Price", PriceBox.Text);
cmd.Parameters.AddWithValue("#Supplier_Name", SupplierNameText.Text);
}
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch
{
MessageBox.Show("Error");
conn.Close();
}
}
catch
{
MessageBox.Show("Error");
conn.Close();
}
}
else
{
MessageBox.Show("Data Connection Failed");
this.Close();
}
}

Related

Show data in datagrid after add new record

I want to show data from my database in dataGridView after saved new record. After I clicked button, the data saved, but not show in datagridview. How can I show that data?
private void btn_add_Click(object sender, EventArgs e)
{
{
if (textBox_tarikh.Text == "" || textBox_resit.Text == "" || textBox_bayaran.Text == "")
{
MessageBox.Show("Please Fill In The Blank");
}
else
{
String bResult = textBox_ic.Text;
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"; // add your conncetion string here
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT Pembayaran (Description, Date, No_Resit, Payment, Studentic) VALUES (#Description, #date, #resit, #payment, #val)", connection);
cmd.Parameters.AddWithValue("#val", bResult);
cmd.Parameters.AddWithValue("#Description", label4.Text);
cmd.Parameters.AddWithValue("#date", Convert.ToDateTime(textBox_tarikh.Text));
cmd.Parameters.AddWithValue("#resit", textBox_resit.Text);
cmd.Parameters.AddWithValue("#payment", textBox_bayaran.Text);
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "pembayaran_table");
connection.Close();
dataGridView3.DataSource = ds;
dataGridView3.DataMember = "pembayaran_table";
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved Successfully");
}
catch (Exception ex)
{
//throw new Exception("Error " + ex.Message);
MessageBox.Show("Receipt No. is already use");
}
}
You can try :
private void btn_add_Click(object sender, EventArgs e)
{
string bResult = textBox_ic.Text;
if (textBox_tarikh.Text == "" || textBox_resit.Text == ""||textBox_bayaran.Text == "")
{
MessageBox.Show("Please Fill In The Blank");
}
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd ;
try
{
if(connection.State == ConnectionState.Closed) connection.Open();
cmd = new SqlCommand("INSERT Pembayaran (Description, Date, No_Resit, Payment, Studentic) VALUES (#Description, #date, #resit, #payment, #val)", connection);
cmd.Parameters.AddWithValue("#val", bResult);
cmd.Parameters.AddWithValue("#Description", label4.Text);
cmd.Parameters.AddWithValue("#date", Convert.ToDateTime(textBox_tarikh.Text));
cmd.Parameters.AddWithValue("#resit", textBox_resit.Text);
cmd.Parameters.AddWithValue("#payment", textBox_bayaran.Text);
cmd.Executenonquery();
SqlDataAdapter da = new SqlDataAdapter("Select * from Pembayaran",connection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView3.DataSource = dt;
}
catch(Exception ex)
{
}
finally
{
if(connection.State == ConnectionState.Open) connection.Close();
}
}
You just need to update your DataGridView's Datasource after inserting record to DB.
Firstly, I don't see any data binding code in your snippet such as DataGridView.DataSource = " ", DataGridView.DataBind();
What you can try to do it after inserting data, make use of ##IDENTITY to retrieve the id of what you have inserted. Then make use of the id retrieved to capture the new record.
##IDENTITY
I have noticed in your code snippet, you used the same query.
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
You should write another SqlStatement and call it from SqlDataAdapter
For example:
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");
Populating a DataSet from a DataAdapter

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");
}
}
}

Datagridview with query in C#

I have 2 tables in MySql (privacy , lawsuit_under_500) ,
In privacy i have 2 columns (id , nameofcase ) ,
In lawsuit_under_500 4 columns(id,nameofcase,priceone,pricetwo) ,
I make a form with a datagridview and i want to execute this query :
select privacy.id,lawsuit_under_500.id,privacy.nameofcase, lawsuit_under_500.priceone, lawsuit_under_500.pricetwo
From privacy inner join lawsuit_under_500
where lawsuit_under_500.id=5 and privacy.id=1 || lawsuit_under_500.id=1 and privacy.id=2 || lawsuit_under_500.id=10 and privacy.id=3
ORDER BY privacy.id
In the form i have:
public Form55()
{
InitializeComponent();
}
private void Form55_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have put the tables in my DataSet but I cant figure out how to make it. I tried to make privacyBindingSourse in the datagridview and i added manually 2 buttons for priceone and pricetwo put i cant put the query so i can get the information.
Any ideas/help how to make it ?
BEFORE YOU ANSWER IF YOU HAVE ANY QUESTION PLEASE ASK ME
using MySql.Data.MySqlClient;
MySqlConnection conn = new MySqlConnection("Your MY SQL connection");
MySqlCommand cmd = new MySqlCommand("Your Mysql query");
MySqlDataReader dr=cmd.ExecuteReader();
gridview1.datasource=dr;
gridview1.databind();
// try this also
connectionString = "Your Connection";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("Your Query", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
I made it with this way
private void Form56_Load(object sender, EventArgs e)
{
try
{
MySqlConnection cnn = new MySqlConnection("MY CONNECTION");
cnn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
static public SqlCeConnection OpenSQL()
{
SqlCeConnection cncount = new SqlCeConnection(#"Data Source = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Database.sdf; Password =''");
return cncount;
}
static public DataTable DoSelect( string strSQL)
{
SqlCeConnection cn = OpenSQL();
DataTable dtRetValue = new DataTable();
using (SqlCeDataAdapter da = new SqlCeDataAdapter())
{
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = strSQL;
da.SelectCommand = cmd;
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
try
{
//using (SqlCeDataReader reader = da.SelectCommand.ExecuteReader())
SqlCeDataReader metsDr = da.SelectCommand.ExecuteReader();
dtRetValue.Load(metsDr);
return dtRetValue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error - DoSelect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
}
}
}
}
Insert in Button
string sql1 = "YOURE QUERY ";
DataTable dt1 = SQLcode.DoSelect(sql1);
dgvcompany.DataSource = dt1;

Refreshing Gridview After Button Click

on my asp.net project, how can i refresh my gridview immediately after clicking my button.
my button has update codes.here is the codes;
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL = "UPDATE [bilgiler3] SET [HAM_FM] = ISNULL(MON,0)+ISNULL(TUE,0)+ISNULL(WED,0)+ISNULL(THU,0)+ISNULL(FRI,0)+ISNULL(SAT,0)+ISNULL(SUN,0) WHERE [DATE] BETWEEN #DATE1 AND #DATE2 AND WORK_TYPE='OUT'";
string connStr = WebConfigurationManager.ConnectionStrings["asgdb01ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = strSQL;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#DATE1", Convert.ToDateTime(TextBox1.Text));
comm.Parameters.AddWithValue("#DATE2", Convert.ToDateTime(TextBox2.Text));
try
{
conn.Open();
int i = comm.ExecuteNonQuery();
conn.Close();
if (i > 0)
{
Response.Write(" SUCCESS ");
}
else
{
Response.Write(" ERROR ! ");
}
}
catch (SqlException ex)
{
Response.Write(ex.ToString());
}
}
}
}
you maybe gonna say "you need to bind the data of your gridview" but i couldnt understand the method.
can you help me about it ?
thank you very much.
I would do the following:
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
SqlConnection sc = new SqlConnection("you connection string here Security=True");
private void loadData()
{
try
{
ds.Clear();
SqlCommand sCmd= new SqlCommand("Load your database", sc);
sda.SelectCommand = sCmd;
sda.Fill(ds, "sCmd");
datagrid.DataSource = ds.Tables["sCmd"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
something for c# beginners Youtube
Add this code on your button click
SqlConnection con = new SqlConnection("Connection string from web config");
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter("select * from EmployeeTable", con);
con.Open();
sda.Fill(ds ,"Data");
gridview1.datasource=ds.tables[0];
gridview1.DataBind();
private SqlConnection con;
private SqlConnectionStringBuilder str;
private void Form8_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new SqlConnectionStringBuilder();
str.Provider = "";
str.DataSource = #"source.accdb";
con = new SqlConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from yourTable");
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}
then If you want to refresh the table you put the loaddata(); in the event button_Click hope this help,
DataBind your control on success.
if (i > 0)
{
yourGridView.DataSource=YourDataSource;
yourGridView.DataBind();
Response.Write(" SUCCESS ");
}

when i am inserting a single record, it inserts two records at a time. help please

private void button1_Click(object sender, EventArgs e)
{
Insert();
}
private int Insert()
{
string Query = "insert into person values ('" + textBox4.Text + "','" + textBox5.Text + "')";
string connectionString = #"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=prac;Integrated Security=True";
SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
DataTable dt = new DataTable();
da.Fill(dt);
int RowEffected = cmd.ExecuteNonQuery();
cn.Dispose();
if (RowEffected > 0)
{
MessageBox.Show("Record Affected");
}
GetDBConnection();
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
return 0;
}
public Form1()
{
InitializeComponent();
GetDBConnection();
//Insert();
}
private void GetDBConnection()
{
string connnectionstring = #"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=prac;Integrated Security=True";
SqlDataAdapter da = new SqlDataAdapter("select * from person", connnectionstring);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
comboBox1.DataSource = dt;
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "lname";
}
When you do
da.Fill(dt);
cmd passed to da in it's constructor is executed. That's first time.
Second is in ExecuteNonQuery.
Cmd in sqlDataAdapter should be SELECT command.

Categories

Resources