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");
}
}
}
Related
Building a form application in C# for selling phones as a project. I have two radio buttons which the user checks based on what type of payment method they want cash or card.
How do I insert that data into the database based on what the user selects?
You can try this,
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into sample values(#payment)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#payment", payment.SelectedValue);
if (cn.State == ConnectionState.Closed)
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
lblmsg.Text = "Data entered successfully!!!";
}
I found the answer to my own question if someone needs it
try
{
var connection = getConnection();
connection.Open();
if (CashRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText ="INSERT INTO type_payment(cash,card) values(1,0)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succsefully picked type");
}
else
{
MessageBox.Show("error");
}
}
else if (CardRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText = "INSERT INTO type_payment(cash,card) values(0,1)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succesfully picked type");
}
else
{
MessageBox.Show("Error");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Luka,
Try it below.
Add HTML Markup like:
<asp:CheckBox ID="chkCash" runat="server" />
.cs file add below code.
string Cash = chkCash.Checked ? "Y" : "N";
And send or add value like.
SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Cash) VALUES(#Cash)"))
{
cmd.Parameters.AddWithValue("#Cash", Cash);
}
The problem is, that I am trying to update my database record trough user's input on a Textbox.
The code below shows
protected void Page_Load(object sender, EventArgs e)
{
con1.Open();
try
{
//btn_save.Click += new EventHandler(btn_save_Click);
rs_id = Session["Res_Id"].ToString();
if (!this.IsPostBack)
{
getcategory();
getcuisine();
}
try
{
sitem_id = Session["item_id"].ToString();
if (sitem_id != "")
{
getitemdata();
getaddonprice();
getchoiceprice();
}
}
catch(Exception ex)
{
}
}
catch (Exception ex)
{
Response.Redirect("Default");
}
}
public void getitemdata()
{
try
{
SqlCommand cmd = new SqlCommand("select * from tbl_item where item_id='" + sitem_id + "'", con1);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
string price,status;
txt_iname.Text = dr["item_name"].ToString();
txt_desc.Text = dr["item_description"].ToString();
drp_category.SelectedValue = dr["category_id"].ToString();
cui_drp.SelectedValue = dr["cusine_id"].ToString();
price_chk = dr["pos"].ToString();
status = dr["status"].ToString();
img_nname = dr["item_uname"].ToString();
img_dname = dr["item_img"].ToString();
if (price_chk == "1")
{
chk_price.Checked = true;
div_price.Style["display"] = "none";
div_choice.Style["display"] = "block";
div_addon.Style["display"] = "block";
}
else
{
chk_price.Checked = false;
div_price.Style["display"] = "block";
div_choice.Style["display"] = "none";
div_addon.Style["display"] = "none";
}
if(status=="1")
{
chk_status.Checked = true;
}
else
{
chk_status.Checked = false;
}
update_id = "1";
}
dr.Close();
}
catch(Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
public void getaddonprice()
{
try
{
SqlCommand cmd = new SqlCommand("select vname as add_on_name,price as amt from tbl_price_master where item_id='" + sitem_id + "' and type='2'", con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
grid_addon.DataSource = dt;
grid_addon.DataBind();
}
catch(Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
public void getchoiceprice()
{
try
{
SqlCommand cmd = new SqlCommand("select vname as choice_name,price as amt from tbl_price_master where item_id='" + sitem_id + "' and type='1'", con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
grid_choice.DataSource = dt;
grid_choice.DataBind();
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
public void update()
{
try
{
string ch_status;
if(chk_status.Checked)
{
ch_status = "1";
}
else
{
ch_status = "0";
}
string item_uname = txt_iname.Text + "_" + rs_id;
if (chk_price.Checked == true)
{
if(img_res.HasFile)
{
deleteimg();
getimg();
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#item_img", "Item_Images/" + newFileName);
cmd.Parameters.AddWithValue("#pos", "1");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 21);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert();
price_insert2();
}
else
{
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#pos", "1");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 20);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert();
price_insert2();
}
}
else
{
if (img_res.HasFile)
{
deleteimg();
getimg();
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#item_img", "Item_Images/" + newFileName);
cmd.Parameters.AddWithValue("#pos", "0");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 21);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert3();
}
else
{
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#pos", "0");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 20);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert3();
}
}
Session["item_id"] = null;
update_id = "0";
Response.Redirect("Item_List");
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
Now, just to make sure that all is ok, I tried changing the content of the Textbox named txt_desc. To my surprise, upon clicking the save button the content of the txt_desc Textbox returns to its original content.
Thank you.
Function getitemdata(); is always called. It should be only called on first load of page.
When button is clicked, the data from database is filled again in text_desc by this function.
You should move all code that fills data in input fields from database in !IsPostback
Like
In your page_load()
if (!this.IsPostBack)
{
getcategory();
getcuisine();
getitemdata();
}
Also note following:
Using connection object as global class variable can give you connection management troubles at some point. Move it closer to SqlCommand usage.
Your code is vulnerable to SqlInjection attack. Use #variables instead of string concatenation for SQL query in SqlCommand
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();
}
}
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;
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.