I got the problem. I want to update the data to the database, but the database won't update.
Here is the code:
else if (firstForm.textBox1.Text == "Seranne")
{
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
}
index += 1;
}
conn.Close();
dReader.Close();
}
}
private void UpdateQuantity()
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
EDIT: (The function UpdateQuantity in below is when the user click Update button) and i am getting an error when i click the Update button, here is the error: Syntax error (missing operator) in query expression '[Code] IN ('.
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbDataReader dReader;
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
dReader = cmd.ExecuteReader();
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (", conn);
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd.ExecuteNonQuery();
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
index += 1;
dReader.Close();
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
Above code all worked, excepts for updating the Quantity to the database. What I mean is, I set the Quantity in database to 100, when I set Quantity to 10 in my program and update it, the database should be update the Quantity to 90 (because 100 - 10), but it is still at 100.
Could I wrong somewhere?
Here is the link of the screenshots: (ScreenShot 1) https://www.dropbox.com/s/rph5iuh371rc9ny/Untitled.png
(ScreenShot 2) https://www.dropbox.com/s/5q8pyztqy7ejupy/Capture.PNG
In the Screenshot 1, I already set the quantity to 10 and the messagebox show that the data has been updated successfully and the data in the database supposed to be 90 (because 100-10). But, in the Screenshot 2 where the database is, the Quantity still at 100.
Thanks in advance!
Your update query
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
doesn't appear to be completed in the code you have posted. My guess is that you are getting a syntax error which your code is not trapping and displaying.
Related
Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.
Im very new on programming and Im having a difficult time thinking on how can I add new Item when Item Code does not exist on the database. It seems to run smoothly until I add else statement. here my code:
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode=itemcode");
command.Connection = con;
command.Parameters.AddWithValue("#itemcode", txtItem.Text);
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows == true)
{
OleDbCommand cmd = new OleDbCommand(#"Update TblInventory set Quantity = Quantity + #Quantity
WHERE ItemCode = #itemcode");
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Quantity",Convert.ToInt32(txtQuantity.Text));
cmd.Parameters.AddWithValue("#itemcode", txtItem.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Saved !");
}
else
{
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
MessageBox.Show("New Data Added");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
One of the best way to find existing record in database is to count the number of given record criteria.
OleDbCommand command = new OleDbCommand(#"Select COUNT(ItemCode) from
TblInventory where ItemCode= #itemcode");
Then use ExecuteScalar() instead of ExecuteReader()
Int32 count = (int32) command.ExecuteScalar();
ExecuteScalar() returns the first column of the first row of your query result which is the count of your itemCode. You can read in this link for more information.
Then you can do the simple conditional logic.
if (count > 0) // means that itemCode has 1 or more record count found in the db.
{
// Do the update logic here..
}
else
{
// Do the insert logic here...
}
I already found the answer.
FROM THIS:
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode=itemcode");
TO THIS:
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");
how to update selected data in mysql in c#?
this is my code when i press button2 . all data "jumlah_product" minus two.
i want to make just minus two "jumlah_product" in selected data.
private void button2_Click_1(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost;Database=maindata;Uid=root;pwd=firmandoang;";
string Query = "select * from maindata.product_database where idproduct = '" + this.textBox1.Text + "' OR namaproduct LIKE '" + this.textBox1.Text + "'";
MySqlConnection conn = new MySqlConnection(MyConnectionString);
MySqlCommand command = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
myReader = command.ExecuteReader();
try
{
if (myReader.Read())
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[1].Value = myReader.GetString("namaproduct");
row.Cells[2].Value = myReader.GetString("hargaproduct");
int count = Convert.ToInt32(textBox2.Text);
int price = Convert.ToInt32(row.Cells[2].Value);
row.Cells[3].Value = count;
row.Cells[4].Value = price *= count;
dataGridView1.Rows.Add(row);
string update = "UPDATE maindata.product_database SET jumlah_product=(jumlah_product - '" + count + "')";
MySqlCommand cmd = new MySqlCommand(update, conn);
MySqlDataReader reader;
myReader.Close();
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
}
else
{
MessageBox.Show("No Data ");
}
sorry for bad english . I hope you understand :)
I am getting an error while updating the data, the error says: "Syntax error (missing operator) in query expression '[Code] IN('."
Here is the code where i am getting an error at:
OleDbDataReader dReader = cmd.ExecuteReader();
Here is the full code of the function that the error is appear:
private void UpdateQuantity()
{
int index = 0;
string command = "UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN(";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(command, conn);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = Convert.ToDecimal(dReader["Quantity"].ToString()) - textBoxQuantityContainer[index].Value;
}
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
index += 1;
}
conn.Close();
dReader.Close();
}
Here is the previous code where the query expression "Code IN":
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
index += 1;
}
conn.Close();
dReader.Close();
Thanks a bunch!
OK, just keep your code and change this:
for (int i = 1; i < 17; i++) {
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + codeValue + ",";
}
}
query = query.TrimEnd(',') + ")";
before proceed you better create integer list out of textBoxCodeContainer values, say it as integers
then
string command = "UPDATE [Seranne] SET [Quantity] =? WHERE [Code] IN(" + string.Join(", " , integers) +")";
Generate integer list as below
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
int codeValue;
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
I can retrieve data from the database and it works now, but only on the first line (both description and code are correct and based on the database).
On the second line, the description is not based on the database, however it display the description for the first line, even though the code for first and second line are different. How do I fix that?
Here is some code:
private void UpdateDatas()
{
int codeValue = 0;
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(
"SELECT [Description], [Price] FROM [Data] WHERE [Code]=#Code", conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else
{
MessageBox.Show("Error");
}
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[0][0].TextLength != 0)
{
this.textBoxDescContainer[0][0].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][0].Text = dReader["Price"].ToString();
}
if (textBoxCodeContainer[0][1].TextLength != 0)
{
this.textBoxDescContainer[0][1].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][1].Text = dReader["Price"].ToString();
}
}
dReader.Close();
conn.Close();
}
Here is the image:
Here is the image of the database:
That's because you processes first record twice in your loop, for both text boxes. Try this as a quick fix:
int index = 0;
while (dReader.Read())
{
if (textBoxCodeContainer[0][index].TextLength != 0)
{
this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
}
index += 1;
}
The second problem, is that you add two values for one parameter (Code) in your query, so the result of the select will contain only one row. You should you the "IN" SQL keyword. The second quick fix would concern your query:
var query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
dReader = cmd.ExecuteReader();
How to parametrize the query with the "IN" clause is another problem - this is just a quick fix to make this work.