i have a problem here.
Here is my case:
I want to update the Quantity value from program based on the value given from program and minus it to the database. For example: i have 100 in Quantity in the database, once i run the program and update the Quantity to 50, the Quantity in the database should be 50.
Here is my problem:
I already can update Quantity value from program to the database, but no matter what's the value that i gave to Quantity in the program, the Quantity value in the database always updating to 0.
Here is the code:
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
string command = "UPDATE [Seranne] SET [Quantity]= " + newVal + " WHERE [Code] IN(" + string.Join(", ", integers) + ")";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbDataReader dReader;
OleDbCommand cmd = new OleDbCommand(command, conn);
conn.Open();
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
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;
cmd.ExecuteNonQuery();
}
index += 1;
}
if (newVal == 0)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sounds.Play();
MessageBox.Show("Cannot Update", "Error");
}
else
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Was Updated Successfully", "Success");
}
dReader.Close();
conn.Close();
}
The newVal value keep appear 0. Because the newVal keep 0, the program show this when i click "Update" button in the program:
if (newVal == 0)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sounds.Play();
MessageBox.Show("Cannot Update", "Error");
}
But when i check in the database, the Quantity value is changed to 0, no matter what is the value that i was given in the program and the newVal keep 0. So, i think the because of newVal is keep appear 0, then the database recognized it and update it based on the newVal, and this code seems not working:
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = Convert.ToDecimal(dReader["Quantity"].ToString()) - textBoxQuantityContainer[index].Value;
cmd.ExecuteNonQuery();
}
Could you guys help me out? Thanks in advance!
EDIT Code:
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
string command;
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbDataReader dReader;
OleDbCommand cmd = new OleDbCommand(command, conn); // error: use of unassigned local variable, if i put "string command = '' ", the program will run, but the command not recognized by system, and the error will be: Command text was not set for the command object.
conn.Open();
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
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;
command = "UPDATE [Seranne] SET [Quantity]= " + newVal + " WHERE [Code] IN(" + string.Join(", ", integers) + ")";
cmd.ExecuteNonQuery();
}
index += 1;
}
if (newVal == 0)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sounds.Play();
MessageBox.Show("Cannot Update", "Error");
}
else
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Was Updated Successfully", "Success");
}
dReader.Close();
conn.Close();
}
change the following like this in while loop,
newVal = Convert.ToDecimal(dReader["Quantity"].ToString()) - textBoxQuantityContainer[index].Value;
string command = "UPDATE [Seranne] SET [Quantity]= " + newVal + " WHERE [Code] IN(" + string.Join(", ", integers) + ")";
cmd.ExecuteNonQuery();
after your while loop , since the 'newVal' is 0 when it was used in query and was updated later on.
Related
I have a code below and it has strange behavior,Line of code after closing of While Loop is not executing. If i write those lines before While loop they got executed. I have searched a lot on this issue but failed.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
} //code after this is not executing
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please Check you Ordered Quantity !");
}
con.Close();
}
}
Actually there was issue that connection state was already Open and i was trying to open it again. So then i used try-catch block it told me that connection is already open. Now i have changed my code and here it is.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
try
{
//con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
}
con.Close();
}
catch(Exception EX)
{
MessageBox.Show(EX.ToString());
}
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
con.Open();
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
check_qty = -1;
}
}
enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}
I am using the same button "Save" to update a table called AnalysisExperiments and also to insert data into a table called "Analysis". however the update is not working. Here is the code:
#region Insert Data into Analysis Table
if (checkIfRepeatedJobNumber(tbJobNumber.Text.Trim()))
{
MessageBox.Show("Job Number is already exist.", "Repeated Data");
return;
}
string query = "insert into Analysis (ID, WellName, EstimatedStartDate, SOWComments, ProgressComments, Field, FocalPoint, StudyCompleted, Company, ReservoirPressure, ReservoirTemp, SelectedSamples) " +
"values (#ID, #WellName, #SamplingDate, #SOWComments, #ProgressComments, #Field, #FocalPoint, #StudyCompleted, #Company, #ReservoirPressure, #ReservoirTemp, #SelectedSamples)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("#ID", tbJobNumber.Text);
cmd.Parameters.AddWithValue("#WellName", tbWellName.Text);
cmd.Parameters.AddWithValue("#SamplingDate", dtpSamplingDate.Text);
cmd.Parameters.AddWithValue("#SOWComments", tbSOW_Comments.Text);
cmd.Parameters.AddWithValue("#ProgressComments", tbProgressComments.Text);
cmd.Parameters.AddWithValue("#Field", tbFieldName.Text);
cmd.Parameters.AddWithValue("#FocalPoint", tbFocalName.Text);
if (radYes.Checked)
cmd.Parameters.AddWithValue("#StudyCompleted", "Yes");
else
cmd.Parameters.AddWithValue("#StudyCompleted", "No");
cmd.Parameters.AddWithValue("#Company", tbCompany.Text);
cmd.Parameters.AddWithValue("#ReservoirPressure", tbReservoirPressure.Text);
cmd.Parameters.AddWithValue("#ReservoirTemp", tbReservoirTemp.Text);
cmd.Parameters.AddWithValue("##SelectedSamples", tbSelectedSamples.Text);
try
{
conn.Open();
int j = cmd.ExecuteNonQuery();
if (j == 1)
{
MessageBox.Show("Done");
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
#endregion
#region update analysis Exp but still no working
#region Update database
try
{ int k = 0;
OleDbDataAdapter da;
da = new OleDbDataAdapter("select* from [AnalysisExperiments]", conn);
string ExpQuery = "update AnalysisExperiments set SampleNumber = #SampleNumber, Status = #Status where ID = '" + tbJobNumber.Text + "' and Experiment = '";
foreach (DataGridViewRow row in dgvExperiments.Rows)
{
ExpQuery += row.Cells["Experiment"].Value.ToString() + "'";
OleDbCommand updateCommand = new OleDbCommand(ExpQuery, conn);
updateCommand.Parameters.Add("#SampleNumber", OleDbType.VarWChar);
MessageBox.Show(row.Cells["SampleNumber"].Value.ToString() + " | " + row.Cells["Status"].Value.ToString() + " | " + row.Cells["Experiment"].Value.ToString());
updateCommand.Parameters["#SampleNumber"].Value = row.Cells["SampleNumber"].Value.ToString();
updateCommand.Parameters.Add("#Status", OleDbType.Boolean);
updateCommand.Parameters["#Status"].Value = row.Cells["Status"].Value;
da.UpdateCommand = updateCommand;
conn.Open();
k = da.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
if (k == 1)
MessageBox.Show("Done");
else
{
MessageBox.Show("Nothing Updated!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
#endregion
knowing that the compiler skips the loop in the update region.
At the second loop the query syntax becomes invalid cause the += that concatenates the previous text with the new one
Dim newQuery = ExQuery + row.Cells["Experiment"].Value.ToString() + "'";
And then use the new string for the ExecuteNonQuery.
Still this approach has many problems. You should separate this code in different methods and use parameters also for the last value
Have you tried to debug the foreach line to see if there are any rows in your dgvExperiments and if they are of type (or subtype of) DataGridViewRow ?
How do i minus data from the program to the database?
I have quantity and description in my database.
The quantity will be 100, and the description of it will be A.
When i type in my program like this (after run the program):
The quantity is 50. and the description of it is A.
The database:
The quantity will be 50 (because minus with the database and my program "100 - 50 = 50", and the description still remains same as A.
How do i do that?
Thanks in advance!
Edit:
I already did like this:
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Value = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0)
{
if (textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
decimal newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (");
}
}
But when i run the program, the quantity loaded exactly the same like in the database, but it can't change, when i type quantity is 50, the program will automatically return to 100 (which is same exactly the quantity in the database)
Why is it like that?
Note: for textbox quantity, i use the Numeric Up Down.
Edit: The full code is on below:
private void UpdateDatas()
{
int codeValue = 0;
int index = 0;
if (firstForm.textBox1.Text == "Seranne")
{
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbDataReader dReader;
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);
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Value = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0)
{
if (textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
decimal newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (");
}
}
index += 1;
}
dReader.Close();
conn.Close();
}
}
private void UpdatePrice()
{
int totalPrice = 0;
int quantity = 0;
int price = 0;
for (int i = 0; i < 17; i++)
{
if (textBoxQuantityContainer[i].Value > 0)
{
quantity = (int)textBoxQuantityContainer[i].Value;
price = Convert.ToInt32(textBoxSubTotalContainer[i].Text);
textBoxTotalContainer[i].Text = (quantity * price).ToString();
}
else
{
textBoxSubTotalContainer[i].Text = "";
textBoxTotalContainer[i].Text = "";
}
}
for (int i = 0; i < 17; i++)
{
if (textBoxTotalContainer[i].TextLength != 0)
{
totalPrice += Convert.ToInt32(textBoxTotalContainer[i].Text);
}
}
textBoxAllTotalContainer.Text = totalPrice.ToString("n2");
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateDatas();
UpdatePrice();
}
}
}
Here is the screenshot:
"Code" displayed in the screenshot above is refer to the database, and also the "Quantity", whenever i type the code that already have in the database, the remaining box are filled up. But, when i change the "Quantity" from 100 to 50, it is automatically like refresh the program to back to 100 again.
cmd = new oledbcommand("select qty from tablename where pid=103");
qtyval = convert.ToInt32(cmd.ExecuteScalar());
if (qtyval != 0 )
{
if (qtyval >= convert.toint32(txtqty.text))
{
newval = qtyval - convert.ToInt32(txtqty.text);
cmd = new oledbcommand("update tablename set qty="+newval+" where pid=103");
}
}
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (");
[This can't be your actual code because it is missing a closing quote and bracket. Please always just copy and paste your actual code.]
WHERE [Code] IN (")
You are attempting to update where the Code is an empty string? It is far more likely to be NULL, so this is one reason why it won't update. However, you haven't executed this cmd, so it won't change anything.
[Do you really intend to update ALL records which don't have a Code ?]
You should also print-out cmd and attempt to execute it from within Access as part of your debugging steps.
Lastly, why are you quoting the Quantity with apostrophes? Presumably, it is a numeric field.
pstrjds, From the code you have provided I am trying to implement that code and the msdn link you provided couple of days ago. I am not sure how to put it together but I am see a message that "The variable name '#ID' has already been declared. Variable names must be unique within a query batch or stored procedurce." Do I need to create a stored procedurce? Can I assume I got the ID bit right as well, where you explained number of times? Thank you.
enter code here
cs.Open();
int remainingStock = 0;
string Query = "SELECT StockA SET QTY = #QTY " + "WHERE ID = #ID;";
SqlCommand cmd = new SqlCommand(Query, cs);
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters["#ID"].Value = 1;
cmd.Parameters.AddWithValue("#ID", Query);
try
{
if (remainingStock == 1)
{
lbqty.Text = "Not enough stocks.";
}
else
{
cmd.CommandText = "UPDATE StockA SET QTY = QTY-1
WHERE ID=1";
int rowsUpdated = cmd.ExecuteNonQuery();
remainingStock--;
string remaining = "Remaining stocks: " +
remainingStock.ToString();
txQty.Text = remaining;
lbqty.Text = remaining;
DGA.Update(); //this is DataGridView
}
Int32 rowsAffected = cmd.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
cs.Close();
}
The problem is that you don't check for the case where ret == -1. Changing your second if-statement to if(ret < 1) should fix your issue.
Also, directly after the line cmd.ExecuteNonQuery(); add ret--; to sync the ret variable with the value that is now in the database.
I think this is your problem - you make ret - 1 while processing and then
txtQty.Text = "Remaining stocks: " + (ret - 1).ToString();
lbqty.Text = "Remaining stocks: " + (ret - 1).ToString();
that shows one less item. Try making it:
txtQty.Text = "Remaining stocks: " + ret.ToString();
lbqty.Text = "Remaining stocks: " + ret.ToString();
After reading your question again, I am more convinced that the comment I posted is actually the problem. You said in your question that your quantity is not going down. If you look at the return value from the line:
cmd.ExecuteNonQuery();
in your else statement I believe you will get a value of 0. This indicates that no records where updated. I believe the problem is exactly related to your query. If you connect to your database with a utility such as LINQPad or the Sql Management studio and run the query you have listed in your code I think you will find it is not updating anything. I highly suspect that your inventory is not being stored in a table called tblContacts. Which is why you can't select a quantity from it nor update a quantity in it.
Edit:
Meant to mention this initially and then got sidetracked and forgot to add it. I would put your SqlCommand in a using statement. The SqlCommand object is disposable and so it is good practice to place disposable objects in a using statement or in some sort of try/finally pattern where they can be cleaned up.
Additional edit - restructuring your code:
cs.Open();
int remainingStock = 0;
string Query = "SELECT QTY from tblInventory WHERE ID=19";
using(SqlCommand cmd = new SqlCommand(Query, cs))
{
var result = cmd.ExecuteScaler();
if (result != null)
{
string str = result.ToString();
if (!string.isNullOrWhiteSpace(str))
{
// NOTE: It would probably be safer to use int.TryParse here
remainingStock = Convert.ToInt32(cmd);
}
if (remainingStock == 0)
{
lbqty.Text = "Not enough stocks.";
}
else
{
cmd.CommandText = "UPDATE tblInventory SET QTY = QTY-1 WHERE ID=19";
int rowsUpdated = cmd.ExecuteNonQuery();
remainingStock--;
if (remainingStock == 1)
{
lbqty.Text = "Re-order. Remaining stocks: 1";
}
else
{
string remaining = "Remaining stocks: " + remainingCount.ToString();
txtQty.Text = remaining;
lbqty.Text = remaining;
}
}
}
else
lbqty.Text = "No stock for contact";
}
dgUpdate();
}
cs.Close();
Your application flow should be as following;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection("Data Source=.; Integrated Security=SSPI; Initial Catalog=FA");
SqlCommand cmd = new SqlCommand();
cmd.Connection = c;
c.Open();
// get remaining stocks
cmd.CommandText = "SELECT Qty from TEST WHERE Id=1";
int ret = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (ret == 0)
{
Label1.Text = "Not enough stocks.";
}
else
{
cmd.CommandText = "UPDATE TEST SET Qty = Qty-1 WHERE Id=1";
cmd.ExecuteNonQuery();
if (ret == 2)
{
Label1.Text = "Re-order. Remaining stocks: 1";
}
else
{
Label1.Text = "Remaining stocks: " + (ret-1).ToString();
}
}
c.Close();
}
The fist thing i can see is that this in not right
if (ret == 1)
{
lbqty.Text = "Re-order. Remaining stocks: 1";
dgUpdate();
}
else
should be
if (ret - 1 == 1)
{
lbqty.Text = "Re-order. Remaining stocks: 1";
dgUpdate();
}
else
because when the value you read is 1 and you decrease it its 0.