The program I have written is a register, which when a bar code is a scanned, will go to the database and pull out the persons name and I.D. No. and also list a "Time In:" at which time they scanned in. And then when they scan a second time it will add a part "Time out:" like such:
Peters, Alastair (242242) Time In : 14:50 Time Out : 14:50 Time In : 14:50
What i am looking for it to do is when i first scan in you will see :
Peters, Alastair (242242) Time In : 14:50
and then when you scan a second time it will add in the Time Out : and then remove the entire line and store it in a second listbox, so it does not show when the person is not in.
And then when the person scans in (the 3rd time) it will re-list the previous line, but with the new Time In
Any suggestions or ideas would be very helpful!
Here is my code:
private string CreateNewEntry(string current)
{
var indexIn = current.LastIndexOf("Time In : "); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("Time Out : "); // Get the last index of the word out
if (indexOut > indexIn)
{
return current + " "+"Time In : "; // if the last "out" comes after the last "in"
}
else
{
// If the last "in" comes after the last "out"
return current + " " +"Time Out : ";
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
bool found = false;
foreach (var item in listBox1.Items)
{
var entry = item.ToString();
if (entry.Contains(returnValue.ToString()))
{
listBox1.Items.Remove(item);
listBox1.Items.Add(CreateNewEntry(entry) + DateTime.Now.ToString("HH:mm"));
found = true;
break;
}
}
if (!found)
{
listBox1.Items.Add(returnValue + " " + "Time In : " + DateTime.Now.ToString("HH:mm"));
}
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
SaveFile.WriteLine(item.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
}
I understand that the starting bit (e.g., "Peters, Alastair (242242)") is unique and remains constant; in that case, you can use FindString. Sample Code:
int curIndex = listBox1.FindString("Peters, Alastair (242242)");
string wholePetersRecord = "";
if (curIndex >= 0)
{
wholePetersRecord = listBox1.Items[curIndex].ToString();
listBox1.Items.RemoveAt(curIndex);
}
This code will find, store in wholePetersRecord and delete the first item starting with "Peters, Alastair (242242)" ("Peters, Alastair (242242) Time In : 14:50 Time Out : 14:50 Time In : 14:50", for instance).
Related
Good Day.
I have a stock list in mysql database
I then have a windows form where i can allocate stock to a certain job, i do this by pulling all from my parts list in mysql and checking if the item selected by the user is in stock, i then add that item to a list using listbox.Items.Add(myitem). In also ass the quantity the user wants to a different list.
When I allocate the stock to a job i create one string separated by ',' and store that to mysql and the same with my quantites resulting is a parts string that looks like: 'PART001,PART002,PART003' and my quantities like: '2,1,3'.
I then add that to a request list which the admin needs to approve.
My problem comes in where the request form is loaded, I pull these parts and quantity lists from mySql and split them wit myString.Split(',');
And I then just add them to another listbox, HOWEVER when i get the quantities that my stock table has available, I loop over the part numbers and pull the quantities but if I for example have my first part as item 3 in my stock table and my second item as my 1st item in my stock list, it will assign item 1's quantity to my item 3. So basically my loop does not assign the right values.
Here is my code for checking the values
ListBox lb = PartsListBox;
ListBox lbq = PartsQuanListBox;
String query = "SELECT * FROM parts WHERE partnum = '"+PartsSelectCb.Text.Trim()+"'";
String partnum = "N/A";
int quan = 0;
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
partnum = (String)dr["partnum"];
}
con.Close();
if(PartsSelectCb.Text == partnum)
{
quan = int.Parse(textBox1.Text);
if (quan > 0)
{
if (!lb.Items.Contains(PartsSelectCb.Text.Trim()))
{
lb.Items.Add(PartsSelectCb.Text.Trim());
lbq.Items.Add(textBox1.Text.Trim());
}
}
}
And here is my code for inserting those values into my request table
private void SendRequest()
{
String dte = DateTime.Now.ToShortDateString();
String g = "";
String h = "";
String a = "";
String b = "";
if (PartsListBox.Items.Count > 0)
{
foreach (var item in PartsListBox.Items)
{
g += item.ToString() + ",";
}
h = g.Substring(0, g.Length - 1);
}
if (PartsQuanListBox.Items.Count > 0)
{
foreach (var itemt in PartsQuanListBox.Items)
{
a += itemt.ToString() + ",";
}
b = a.Substring(0, a.Length - 1);
}
String query = "INSERT INTO partsbook VALUES (NULL,'" + h + "','" + b + "','"
+ ReqTxt.Text.Trim() + "','" + userN + "','" + dte + "','" +""+"','"+ "REQUEST" + "')";
MySqlConnection dataCon = new MySqlConnection(conString);
dataCon.Open();
MySqlCommand cmd = new MySqlCommand(query, dataCon);
try
{
cmd.ExecuteNonQuery();
pmf.CheckRequests();
this.Close();
}
catch (Exception r)
{
MessageBox.Show("ERROR :" + r.Message.ToString());
}
dataCon.Close();
MessageBox.Show("REQUEST SENT");
this.Close();
}
Then on the request side
private void GetStock()
{
String query = "SELECT * FROM parts";
String qtys = "";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String nme = (String)dr["partnum"];
foreach(var item in UPartsListBox.Items)
{
if(item.ToString() == nme)
{
int q = (int)dr["qty"];
qtys += q.ToString() + ",";
}
}
}
con.Close();
string[] words = qtys.Split(',');
foreach(var word in words)
{
if(word != "")
{
SPartsQuanListBox.Items.Add(word);
}
}
}
User Request:
Admin View:
Stock Table:
I 'm dealing with a query which results in above mentioned error when called with no or limited search string.
The table is 30k records big and when the query is fired with no search string I would expect the database to return all records and have Visual Studio put them in a table (ASP.net), however, if the query is fired like above the StackOverflow error is returned :(
If I fire the query with a more specific search string the script seems to work normal and results are being returned as expected.
I have been googling and all seems to point to an infinite loop or recursion but returning records make me believe it might be another problem.
The query:
SqlConnection conn = new SqlConnection(_cstring);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
SqlDataReader dr;
if (mode == "zoek_met_zoekterm")
{
cmd.CommandText = "select W1.id, W1.soort_brief, W1.omschrijving, W1.referentie, W1.url, W1.factuur, W3.naam, W3.klantnummer, W4.omschrijving AS w4_omschr, W4.referentie AS w4_ref, substring(W1.referentie,6,2) as w1_jaar, W1.parent AS w1_parent from brief W1 left join brief W4 on W1.parent = W4.id join klant W3 on W3.klantnummer = W1.klantnummer where W1.referentie in (select referentie from brief where substring(referentie,6,2) = #jaar) and (W3.klantnummer like #zoekterm or W1.referentie like #zoekterm or W1.omschrijving like #zoekterm or W3.naam like #zoekterm or W4.omschrijving like #zoekterm) order by W1.id";
cmd.Parameters.Clear();
cmd.Parameters.Add("#zoekterm", SqlDbType.VarChar).Value = "%" + (string)parameters["zoekterm"] + "%";
string jaar = parameters["jaar"].ToString();
jaar = jaar.Substring(2, 2);
cmd.Parameters.Add("#jaar", SqlDbType.VarChar).Value = jaar;//(Int32)parameters["jaar"];
base.LogQuery(cmd);
dr = cmd.ExecuteReader();
while (dr.Read())
{
CBrief brief = new CBrief();
brief.Id = dr.GetInt32(0);
brief.SoortBrief = (Enums.SoortBrief)dr.GetInt32(1);
brief.Omschrijving = Functies.Decrypt(dr.GetString(2), EncryptData);
brief.Referentie = Functies.Decrypt(dr.GetString(3), EncryptData);
brief.Url = Functies.Decrypt(dr.GetString(4), EncryptData);
brief.Factuur = (Enums.SoortDocument)dr.GetInt32(5);
brief.Klantnummer = dr.GetInt32(7);
if (dr.GetString(2).Length == 0)
{
if (!dr.IsDBNull(9) && !dr.IsDBNull(8))
brief.Omschrijving = dr.GetString(9) + " " + dr.GetString(8);
}
ret_value.Add(brief);
}
dr.Close();
dr.Dispose();
}
And the function that calls the query:
public List<CBrief> GetBriefOverzicht(string zoekterm, int jaar)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("zoekterm", zoekterm);
parameters.Add("jaar", jaar);
if (zoekterm.Length == 0)
{
return _dal.brief_search(parameters, "geen_invoer");
}
return _dal.brief_search(parameters, "zoek_met_zoekterm");
}
And last but not least the function that builds the table to display in the web application:
protected void Bzoeken_Click(object sender, EventArgs e)
{
string zoekterm = TBzoekterm.Text;
DateTime nu = DateTime.Now;
int jaar = nu.Year;
List<CBrief> brieven = br_rbs.GetBriefOverzichtWijzigen(zoekterm);
StringBuilder overzicht = new StringBuilder("<table class=\"tabel-beheer-1\">");
foreach (CBrief b in brieven)
{
List<CBijlage> bijlagen = new List<CBijlage>();
CKlant k = sec.GetKlant(b.Klantnummer);
string klantnaam = k.Naam;
string richting = "";
if (b.OmschrijvingAanwezig == true)
{
bijlagen = br_rbs.GetBijlagenBrieven(b.Id);
}
if (b.SoortBrief == Enums.SoortBrief.Inkomend) richting = "van: "; else richting = "naar: ";
// MG10082017 Ik heb hier twee icoontjes in elkaar geflanst om te testen. Deze moeten nog aangepast worden zodat ze in het geheeel passen.
overzicht.AppendLine("<tr><td><img src=\"/images/bg/document.jpg\" alt=\"open document\"></td><td><img src=\"/images/bg/detail.jpg\" alt=\"details\"></td><td><b>" + b.Referentie + "</b></td><td><i>" + b.SoortBrief.ToString() + " " + richting + "</i> " + klantnaam + "</td><td><b> " + b.Factuur.ToString() + ":</b> " + b.Omschrijving /*+"</td><td>"*/);
if (bijlagen.Count > 0)
{
foreach (CBijlage bijl in bijlagen)
{
overzicht.AppendLine("</br> " + bijl.Naam + "");
}
}
}
overzicht.AppendLine("</td></tr></table>");
Loverzicht.Text = overzicht.ToString();
}
The error usually points to: System.Web.dll or w3wp.exe (when not ran in debug mode). If my assumption is wrong and it seems to be an infinite loop or recursion, how am I going to find this?
The query works flawless in MS-SQL management console.
The Problem is not an infinite loop!
The Problem lies in the UI.
You can't display 30k units at once without a StackOverflow-Exception.
You should call pages of maybe 20 or 30 units at once with an pageIndex.
This way, your application will perform better and avoid such errors.
Whenever I try to update my database, the result ends up being 0.
If I do it in HeidiSQL, it updates just fine, so I know it's not the query.
I have my suspicion that it has to do with the parameters, but I'm unsure regarding that.
I tried with both # and ?, but neither have worked.
MySqlCommand Command = new MySqlCommand("UPDATE `users` SET `cash`=#Cash,
`distance_driven`=#DistanceDriven, `jobs_done`=#JobsDone,
`job_rank`=#JobRank WHERE `username`='#Username';"
, Connection);
Command.Parameters.AddWithValue("#Cash", Cash);
Command.Parameters.AddWithValue("#DistanceDriven", DistanceDriven);
Command.Parameters.AddWithValue("#JobsDone", JobsDone);
Command.Parameters.AddWithValue("#JobRank", JobRank);
Command.Parameters.AddWithValue("#Username", UName);
int result = Command.ExecuteNonQuery(); // result should be 1
Console.WriteLine(result); // ends up being 0
The connection opens fine, but I have no idea why it won't execute the query with the parameters.
Here is the function that requires this update:
public void UpdateUserInfo(object sender, ElapsedEventArgs evt, string uUName)
{
bool cont = false;
Console.WriteLine("UUI 1: " + evt.SignalTime); // gets here fine
try
{
Console.WriteLine("UUI 2: " + evt.SignalTime); // gets here fine
Database database = new Database();
database.Connect();
if (database.UpdateUserData(uUName, TotalCashWallet, TotalDistanceDriven, JobsDone, JobRank))
{
cont = true;
Console.WriteLine("UUI 3: " + evt.SignalTime); // doesn't get here
}
if (cont == true)
{
cont = false;
Console.WriteLine("UUI 4: " + evt.SignalTime);
if (database.UpdateUserBank(uUName, BankInfo.Money, BankInfo.BonusPercentage, BankInfo.BonusLevel))
{
UserInfoUpdated = true;
Console.WriteLine("UUI 5: " + evt.SignalTime);
UserInfoUpdatedTimer.Enabled = true;
return;
}
}
UserInfoUpdated = false;
return;
}
catch (Exception e)
{
Console.WriteLine("UUI 6: " + evt.SignalTime);
Console.WriteLine(e.Message);
ErrorHandler.WriteToLog(e.StackTrace);
ErrorHandler.WriteToLog(e.Message);
ErrorHandler.WriteToLog("------------------------------");
}
return;
}
It doesn't get to the catch part, so it won't log anything.
I tried with both Exception and MysqlException, but it doesn't catch an error.
Doing it the unsafe way works
MySqlCommand Command = new MySqlCommand("
UPDATE `users`
SET `cash`=" + Cash + ",
`distance_driven`=" + DistanceDriven + ",
`jobs_done`=" + JobsDone + ",
`job_rank`=" + JobRank + "
WHERE `username`='" + UName + "';"
, Connection);
You don't need the single quotes around string parameters. Use this query instead:
string query = #"
UPDATE `users` SET
`cash`=#Cash,
`distance_driven`=#DistanceDriven,
`jobs_done`=#JobsDone,
`job_rank`=#JobRank
WHERE
`username`=#Username"
MySqlCommand command = new MySqlCommand(query, Connection);
My registration program logs people in with their name, id and "Time In:" when they scan themselves in, and hides them, but adds "Time Out: " to their name, and vice versa. What im looking to do is every time the person scans themselves "In" I want it to look at the Time "In"'s amd "out"'s and calculate thr total time IN the office.
Attached is the code :
private string CreateTimeEntry(string current)
{
var indexIn = current.LastIndexOf("Time In : "); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("Time Out : "); // Get the last index of the word out
string timeIn = current + " " + "Time In : ";
string timeOut = current + " " + "Time Out : ";
if (indexOut > indexIn)
{
// if the last "out" comes after the last "in"
return timeIn;
}
else
{
// If the last "in" comes after the last "out"
return timeOut;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
bool found = false;
System.DateTime resultTime1 = new System.DateTime(;
foreach (var item in listBox1.Items)
{
var itemEntry = item.ToString();
string newEntry = CreateTimeEntry(itemEntry) + DateTime.Now.ToString("HH:mm") + " " + "Total Time: " + resultTime1 ;
if (itemEntry.Contains(returnValue.ToString()))
{
var indexIn = itemEntry.LastIndexOf("Time In : ");
var indexOut = itemEntry.LastIndexOf("Time Out : ");
if (indexOut > indexIn)
{
listBox2.Items.Remove(item);
listBox1.Items.Add(newEntry);
found = true;
break;
}
else
{
listBox1.Items.Remove(item);
listBox2.Items.Add(newEntry);
found = true;
break;
}
}
}
if (!found)
{
string newEntry2 = "";
foreach (string str in listBox2.Items)
{
var itemEntry2 = str;
newEntry2 = CreateTimeEntry(itemEntry2) + DateTime.Now.ToString("HH:mm");
//if (listBox2.Items.Contains(returnValue.ToString()))
if (listBox2.Items.Contains(str) && str.Contains(textBox1.Text))
{
var indexIn = itemEntry2.LastIndexOf("Time In : ");
var indexOut = itemEntry2.LastIndexOf("Time Out : ");
if (indexOut > indexIn)
{
listBox2.Items.Remove(str);
listBox1.Items.Add(newEntry2);
found = true;
break;
}
}
}
var itemEntry = listBox1.Items.ToString();
var itemEntry1 = listBox2.Items.ToString();
if (!listBox1.Items.Contains(newEntry2))
{
listBox1.Items.Add(returnValue + " " + "Time In : " + DateTime.Now.ToString("HH:mm"));
}
}
}
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item1 in listBox1.Items)
SaveFile.WriteLine(item1.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
You can get the difference between two DateTime objects using the following:
TimeSpan timePassed = timeOut.Subtract(timeIn);
where timeOut and timeIn are DateTime objects.
If you need the difference (or either of the times) displayed somewhere as a string, I would recommend converting them to strings only after doing the calculations that you need. Always work with strongly typed objects when possible.
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.