Foreach loop not reaching going further than first panel items - c#

It seems to me that my foreach loop is not reaching my second panel or something is making it skip the items in the loop.
Here is the creating of the panels and loop(I know the SQL is vulnerable to injections but for the sake of making the question shorter I just used SQL):
This is what is created for every product in the product table:
Label lbName = new Label();
lbName.Text = name + "\n" + row[7].ToString();
lbName.Height = 40;
lbName.Width = 150;
lbName.Name = name + row[7].ToString();
lbName.Location = new Point(ptX, ptY);
pt.Controls.Add(lbName);
Label lbID = new Label();
lbID.Text = row[0].ToString();
lbID.Height = 40;
lbID.Width = 150;
lbID.Name = "ID" + name + row[7].ToString();
lbID.Location = new Point(ptX, ptY);
lbID.Visible = false;
pt.Controls.Add(lbID);
TextBox txtStockCount = new TextBox();
txtStockCount.Text = "0";
txtStockCount.Height = 40;
txtStockCount.Width = 100;
txtStockCount.Name = "txtTS" + name + row[7].ToString();
txtStockCount.Location = new Point(ptX + 150, ptY);
txtStockCount.GotFocus += txtStockCount_GotFocus;
txtStockCount.KeyPress += txtStockCount_KeyPress;
txtStockCount.LostFocus += txtStockCount_LostFocus;
pt.Controls.Add(txtStockCount);
TextBox txtBroken = new TextBox();
txtBroken.Text = "0";
txtBroken.Height = 40;
txtBroken.Width = 100;
txtBroken.Name = "txtTB" + name + row[7].ToString();
txtBroken.Location = new Point(ptX + 300, ptY);
txtBroken.GotFocus += txtStockCount_GotFocus;
txtBroken.KeyPress += txtStockCount_KeyPress;
txtBroken.LostFocus += txtStockCount_LostFocus;
pt.Controls.Add(txtBroken);
TextBox txtRecieve = new TextBox();
txtRecieve.Text = "0";
txtRecieve.Height = 40;
txtRecieve.Width = 100;
txtRecieve.Name = "txtTR" + name + row[7].ToString();
txtRecieve.Location = new Point(ptX + 450, ptY);
txtRecieve.GotFocus += txtStockCount_GotFocus;
txtRecieve.KeyPress += txtStockCount_KeyPress;
txtRecieve.LostFocus += txtStockCount_LostFocus;
pt.Controls.Add(txtRecieve);
Label lbDifference = new Label();
lbDifference.Text = " 0 ";
lbDifference.Height = 40;
lbDifference.Width = 150;
lbDifference.Name = "lblDiff" + name + row[7].ToString();
lbDifference.Location = new Point(ptX + 600, ptY);
pt.Controls.Add(lbDifference);
Button btnConfirm = new Button();
btnConfirm.Text = "Confirm";
btnConfirm.Height = 30;
btnConfirm.Width = 80;
btnConfirm.Name = "btnConfirm" + name + row[7].ToString();
btnConfirm.Location = new Point(ptX + 750, ptY);
btnConfirm.Click += btnConfirm_Click;
pt.Controls.Add(btnConfirm);
and the reading the panels to update the database from the text boxes:
private void txtStockCount_LostFocus(object sender, EventArgs e)
{
TextBox txtB = (sender as TextBox);
string name = txtB.Name.Remove(0,5);
string prodID = "";
string QtyToday = "";
string QtyBD = "";
string QtyRev = "";
string table = "";
foreach (Panel p in pnls)
{
IEnumerable<Label> labels = p.Controls.OfType<Label>();
foreach (Label label in labels)
{
string Compare = label.Name.Remove(0, 2);
if (name == Compare)
{
prodID = label.Text;
if (Regex.IsMatch(Compare, #"^[a-hA-H]"))
{
table = "ProductHistoryAH";
}
else if (Regex.IsMatch(Compare, #"^[i-qI-Q]"))
{
table = "ProductHistoryIQ";
}
else if (Regex.IsMatch(Compare, #"^[r-zR-Z]"))
{
table = "ProductHistoryRZ";
}
}
}
string sql = "Select * From Product WHERE ProdID = '" + prodID + "'";
DataTable dtP = db.GetDataTable(sql);
IEnumerable<TextBox> textBoxes = p.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxes)
{
string name1 = textBox.Name.Remove(0, 5);
label2.Text = name1;
if (name == name1)
{
if (textBox.Name == "txtTS" + dtP.Rows[0][1].ToString() + dtP.Rows[0][7].ToString())
{
QtyToday = textBox.Text;
}
if (textBox.Name == "txtTB" + dtP.Rows[0][1].ToString() + dtP.Rows[0][7].ToString())
{
QtyBD = textBox.Text;
}
if (textBox.Name == "txtTR" + dtP.Rows[0][1].ToString() + dtP.Rows[0][7].ToString())
{
QtyRev = textBox.Text;
}
}
}
string sql1 = "Select * From " + table + " WHERE ProdID = '" + prodID + "' AND ProdHDate = '" + DateTime.Today.Date.ToShortDateString() + "'";
DataTable dt = db.GetDataTable(sql1);
if (dt.Rows.Count == 0)
{
dbh.addnewstockhistory(ph);
}
else if (dt.Rows.Count > 0)
{
dbh.updatestockhistory(ph);
}
}
}
Everything works 100%, it inserts and updates data with ease, with the first panel but no other textboxes on the other panels work.
The error lies in the foreach panel loop, the foreach loops inside the panel loop. It says there is a syntax error near the where of string sql1. But what i dont understand is that it works for the first panel but non of the other panels and it does have the prodID, I know this cause i placed the statement in a label just to see how it looks.
Please help. Ask for anything if you need.

I think I solved it. All I had to do was check if the panel is the panel hosting the control by checking if the panel was the buttons parent and it worked.
if(p == btn.Parent)
{
//Do my stuff
}
in my foreach panel loop.

Related

Visual Studio Database Not Updating

I am working on a school project and for some reason my mysql database doesn't update despite no of row changed is more than 0 and triggering the Update sucessful alert. It also manage to only update my image data from my fileupload.
**admin_products_details_edit.aspx.cs**
protected void btn_ProdEdit_Click(object sender, EventArgs e)
{
int result = 0;
string image = "";
if (FileUpload_ProdImg.HasFile == true)
{
image = "images\\" + FileUpload_ProdImg.FileName;
img_result.ImageUrl = FileUpload_ProdImg.FileName;
}
else
{
image = img_result.ImageUrl;
}
Product Prod = new Product();
string datProdID = lbl_ProdID.Text;
string datProdName = tb_ProdName.Text;
string datProdDesc = tb_ProdDesc.Text;
string datProdImg = img_result.ImageUrl;
decimal datProdPrice = decimal.Parse(tb_ProdPrice.Text);
int datProdCal = int.Parse(tb_ProdCal.Text);
int datStockLvl = int.Parse(tb_StockLvl.Text);
result = Prod.ProductUpdate(datProdID, datProdName, datProdDesc, datProdImg, datProdPrice, datProdCal, datStockLvl);
if (result > 0)
{
string saveimg = Server.MapPath(" ") + "\\" + image;
FileUpload_ProdImg.SaveAs(saveimg);
Response.Write("<script>alert('Update successful');</script>");
Response.Redirect("admin_products_details.aspx?ProdID=" + datProdID);
}
else
{
Response.Write("<script>alert('Update fail');</script>");
}
}<-The code for the button edit event trigger
**Product.cs**
...public int ProductUpdate(string upID, string upName, string upDesc, string upImg, decimal upPrice, int upCal, int upstkLvl)
{
string queryStr = "UPDATE Products SET" + " ProdName = #productName, " + " ProdDesc = #productDesc, " + " ProdImg = #productImage, " + " ProdPrice = #productPrice, " + " ProdCalorie = #productCal, " + " StockLevel = #productStkLvl " + " WHERE ProdID = #productID";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#productID", upID);
cmd.Parameters.AddWithValue("#productName", upName);
cmd.Parameters.AddWithValue("#productDesc", upDesc);
cmd.Parameters.AddWithValue("#productImage", upImg);
cmd.Parameters.AddWithValue("#productPrice", upPrice);
cmd.Parameters.AddWithValue("#productCal", upCal);
cmd.Parameters.AddWithValue("#productStkLvl", upstkLvl);
conn.Open();
int nofRow = 0;
nofRow = cmd.ExecuteNonQuery();
conn.Close();
return nofRow;
}<-The code for updating the mysql database,located in a different cs file,titled Product.cs
My mysql database table is called Products
Thank you very much for your help in advance.

how to retrive the blob image

i have written a code but its not working properly.first i a trying to make a folder and store the image there but as my database is hosted it creating a problem so i store the image as a blob.kindly help me out where i am doing the mistake. thanks.
public void ItemList_with_images(string value)
{
flowLayoutPanelItemList.Controls.Clear();
// string img_directory = Application.StartupPath + #"\ITEMIMAGE\";
// string[] files = Directory.GetFiles(img_directory, "*.png *.jpg");
try
{
conn.Open();
string sql =
"select distinct Item.Item_id,Item.name,Item.image,Item.cost,Item.price, Category.Name as cat_name from Item" +
" INNER JOIN Category ON Item.Category_id=Category.Category_id" +
" INNER JOIN Ingredients ON Item.Item_id=Ingredients.item_id" +
" INNER JOIN Inventory ON Inventory.Inventory_id = Ingredients.invenotry_id" +
" INNER JOIN inventory_detail ON inventory_detail.inventory_id = Inventory.Inventory_id" +
" where(Item.name like '" + value + "%' and inventory_detail.Quantity > 0 and inventory_detail.loc_id =" + UserInfo.Loc_id + ") " +
"OR (Category.Name like '" + value + "%' and inventory_detail.Quantity > 0 and inventory_detail.loc_id =" + UserInfo.Loc_id + ") ";
dataexe.ExecuteSQL(sql, conn);
DataTable dt = dataexe.GetDataTable(sql, conn);
int currentImage = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dataReader = dt.Rows[i];
Button b = new Button();
//Image i = Image.FromFile(img_directory + dataReader["name"]);
b.Tag = dataReader["Item_id"];
b.Click += new EventHandler(b_Click);
string details = dataReader["Item_id"] +
"\n Name: " + dataReader["name"].ToString() +
"\n Buy price: " + dataReader["cost"].ToString() +
"\n Sell price: " + dataReader["price"].ToString();
b.Name = details;
ImageList il = new ImageList();
il.ColorDepth = ColorDepth.Depth32Bit;
il.TransparentColor = Color.Transparent;
il.ImageSize = new Size(78, 80);
// here i am getting error
il.Images.Add(Image.FromStream(new MemoryStream((byte[]) dataReader["image"])));
// il.Images.Add(Image.FromFile(img_directory + dataReader["image"]));
b.Image = il.Images[0];
b.Margin = new Padding(3, 3, 3, 3);
b.Size = new Size(208, 100);
b.Text.PadRight(4);
b.Text += dataReader["name"].ToString();
b.Text += "\n Price: " + dataReader["price"];
b.Font = new Font("Arial", 9, FontStyle.Bold, GraphicsUnit.Point);
b.TextAlign = ContentAlignment.MiddleLeft;
b.TextImageRelation = TextImageRelation.ImageBeforeText;
flowLayoutPanelItemList.Controls.Add(b);
currentImage++;
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
conn.Close();
}
''''
images are not retriving correctly
I'm not sure why you are using an ImageList, if there is a reason please let me know. That being said, here is a very short (and tested) method which loads an image from a file and assigns it to a button's Image property. Below it is an adaptation of the first method, using the datareader as per your code. this method has not been tested.
public void GetImage()
{
MemoryStream stream = new MemoryStream(File.ReadAllBytes(#"C:\Users\Shai Cohen\Pictures\banana.jpg"));
Image image = Image.FromStream(stream);
button1.Image = image;
}
public void GetImageFromDatareader()
{
MemoryStream stream = new MemoryStream((byte[]) dataReader["image"]));
Image image = Image.FromStream(stream);
button1.Image = image;
}

3 DataGridViews interlinking issues

I am having three Datagridviews in my windows Form. One brings the data of Villages, on clicking any cell, Second Datagridview is populated with Customer Details. On clicking the customer name, third Datagridview must populate and calculate the balance of customer, whether credit is remaining or advance is deposited, now where I am facing problem is the third datagridview.
It specifically throws exception: Object reference set to null.
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
double loansum1 = 0;
double emisum1 = 0;
double dd1 = 0;
double ei1 = 0;
double finalsum = 0;
foreach (DataGridViewRow drr1 in dataGridView3.Rows)
{
if (drr1.Cells[1].Selected == true)
{
string customerid = drr1.Cells[0].Value.ToString();
label1.Text = customerid;
SqlConnection setcon = new SqlConnection(ConfigurationManager.ConnectionStrings["sismanager"].ConnectionString);
using (SqlCommand getsup = new SqlCommand("SELECT Ciid, Cdate, Cparticulars, Ccr, Cdr FROM Customerbills WHERE Cid = #Cid ORDER BY Cdate DESC", setcon))
{
getsup.Parameters.AddWithValue("#Cid", customerid);
SqlDataAdapter drrr = new SqlDataAdapter(getsup);
try
{
setcon.Open();
DataTable data1 = new DataTable();
drrr.Fill(data1);
if (data1.Rows.Count > 0)
{
dataGridView1.DataSource = data1;
dataGridView1.Columns[0].HeaderText = "Bill Number";
dataGridView1.Columns[1].HeaderText = "Bill Date";
dataGridView1.Columns[2].HeaderText = "Particulars";
dataGridView1.Columns[3].HeaderText = "Credit Balance";
dataGridView1.Columns[4].HeaderText = "Cash Balance";
for (int ij = 0; ij < (dataGridView1.Rows.Count); ++ij)
{
dd1 = Double.Parse(dataGridView1.Rows[ij].Cells[3].Value.ToString());
ei1 = Double.Parse(dataGridView1.Rows[ij].Cells[4].Value.ToString());
loansum1 += dd1;
emisum1 += ei1;
}
label4.Text = (Math.Round(loansum1)).ToString();
label5.Text = (Math.Round(emisum1)).ToString();
finalsum = (emisum1 - loansum1);
if (finalsum >= 0)
{
label6.Text = "Rs. " + finalsum + " (Previous Amount Clear)";
}
else
{
label6.Text = "Rs. " + finalsum + " (Previous Amount Due)";
}
}
}
catch (SqlException exx)
{
}
finally
{
setcon.Close();
}
}
}
}
}
The exception error comes at:
dd1 = Double.Parse(dataGridView1.Rows[ij].Cells[3].Value.ToString());
Error Image below; It shows in call stack that the data is coming.

Acces dynamically created controls from other method C#

I'm trying to acces my dynamically created Textbox through the click of a button.
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"]
.Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
var tbAantal = new TextBox { Size = new Size(107, 20),
Name = "tbaantal" + productid};
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
string btnname = button.Name.ToString();
//btnname.Remove(1, 6);
int orderid = Convert.ToInt32(label1lblorderid.Text);
Control tbAantalControl = FindControl("tbAantal" + btnname.Remove(0, 6));
int aantal = Convert.ToInt32(tbAantalControl.Text);
//MessageBox.Show(btnname.Remove(0,6));
string query = "Insert Into orderproduct(idorder, idproduct, aantal)
Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
As you can see, I have already tried to access the Textbox by a FindControl(), But this didn't work. I want the Textbox that has the same last value as the clicked TextBox, I'm trying to do this by cutting the string and paste that in a variable.
Please help.
First of all you are searching for TextBoxes with different names than you create them with (tbAantal... vs. tbaantal...). Together with a recursive Find method that would work.
Neither is that good practice nor is it fast.
Better
Rather than searching for controls by name each time you create them you should implement something that directly let's you retrieve the controls (via some identifier or similar, in your case: via productid).
For example:
Declare a Dictionary<int, TextBox> textBoxes as a local variable. In your loop, add textBoxes.Add(productid, tbAantal); right after your definition of tbAantal.
In btnBestel_Click you can then use this mapping to retrieve the correct TextBox via textBoxes[productid].
I am aware that you don't really have the productid defined in that context.
Instead of using btnname.Remove(0, 6), you should use the Buttons's Tag property and store the productid as extra metadata:
Back in your loop add btnBestel.Tag = productid; at the appropriate position. In btnBestel_Click you can then write textBoxes[(int)button.Tag].
Overall code in that case
Dictionary<int, TextBox> textBoxes = new Dictionary<int,TextBox>();
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"]
.Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
var tbAantal = new TextBox { Size = new Size(107, 20),
Name = "tbaantal" + productid};
textBoxes.Add(productid, tbAantal);
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
btnBestel.Tag = productid;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
int orderid = Convert.ToInt32(label1lblorderid.Text);
Control tbAantalControl = textBoxes[(int)button.Tag];
int aantal = Convert.ToInt32(tbAantalControl.Text);
string query = "Insert Into orderproduct(idorder, idproduct, aantal)
Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
I am not sure you are giving valid control name for search. For checking you should apply break point on the line, to see if you are getting valid control name.
For searching your required control by name you should look into each parent control recursively. FindControl method can be used for the purpose.
Change this:
Control tbAantalControl = FindControl("tbAantal" + btnname.Remove(0, 6));
With this:
Control tbAantalControl = FindControl(this.Controls, "tbAantal" + btnname.Remove(0, 6));
Method that recursive find your required:
private Control FindControl(Control.ControlCollection controlCollection, string name)
{
foreach (Control control in controlCollection)
{
if (control.Name.ToLower() == name.ToLower())
{
return control;
}
if (control.Controls.Count > 0)
{
Control result = FindControl(control.Controls, name);
if (result != null)
{
return result;
}
}
}
return null;
}
Is there any reason why you can't just make tbAantal a form level variable and then reference that in the btnBestel_Click method?
var tbAantal = null;
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"].Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
tbAantal = new TextBox { Size = new Size(107, 20), Name = "tbaantal" + productid};
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
string btnname = button.Name.ToString();
//btnname.Remove(1, 6);
int orderid = Convert.ToInt32(label1lblorderid.Text);
int aantal = Convert.ToInt32(tbAantal.Text);
//MessageBox.Show(btnname.Remove(0,6));
string query = "Insert Into orderproduct(idorder, idproduct, aantal) Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}

How can assign specific timer EventHandler for specific value in c#

I have array of timer.I want timer0 work with 1st dataValue in _dataValues, 2nd timer work with 2nd dataValue in _dataValues, 3rd timer work with 3rd dataValue in _dataValues and etc and also show result in label in windows form.I use System.Windows.Forms.Timer.Here is my code,
void PrepareTimers(List<int> _dataValues)
{
int i = 0;
foreach (int dataValue in _dataValues)
{
timerNames[i] ="timer"+ string.Format("{0}", i);
timer1[i] = new Timer();
t[i] = dataValue.ToString();
a[i] = timer1[i].ToString();
a[i] = t[i];
timer1[i].Tick += new EventHandler(timer_Tick);
timer1[i].Interval = (1000) * (1);
label = new Label();
label.Name = "label_name" + i;
label.Size = new Size(200, 20);
label.Location = new Point(45, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
this.Controls.Add(label);
dict[timer1[i]] = label;
timer1[i].Enabled = true;
timer1[i].Start();
i++;
}
}
private void timer_Tick =(object sender, EventArgs e)
{
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
i = 0;
string u = "UPDATED";
mycon.Open();
foreach (int dataValue in _dataValues)
{
if (a[i] == dataValue.ToString())
{
MySqlCommand cmd = new MySqlCommand("UPDATE sms_data_bankasia set flag = " + (dataValue.ToString()) + " *2 , sendingstatus = '" + u + "' WHERE flag = " + dataValue.ToString() + " LIMIT 1", mycon);
cmd.ExecuteNonQuery();
Console.WriteLine("row update" + dataValue.ToString());
mycon.Close();
mycon.Open();
string sql = "SELECT count(flag) FROM sms_data_bankasia where sendingstatus='UPDATED' AND flag = " + (dataValue.ToString()) + " *2 group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
MySqlDataReader dtr = comd.ExecuteReader();
try
{
while (dtr.Read())
{
Timer t = (Timer)sender;
dict[t].Text = dtr[0].ToString() + " program Updated " + dataValue.ToString();
}
dtr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i++;
}
mycon.Close();
}
But it update 4 row in per sec and every EventHandler work with every dataValue.I want 1st timer update 1 row in 1 sec and show in label that 1row update with 1st dataValue and 2nd timer update 1row in 1 sec and show in another label that 1 row update with 2nd dataValue and so on.What should i do? Any one can help me?
In PrepareTimers assign a tag to each timer: timer1[i] = new Timer(); timer1[i].Tag = i;
Then you can use this in timer_Tick instead of looping through the whole array:
i = (int)((Timer)sender).Tag;
int dataValue = _dataValues[i];
//...
instead of:
i = 0;
foreach (int dataValue in _dataValues)
{
if (a[i] == dataValue.ToString())
//...

Categories