Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Can't conect button click with buton control

My code for button


Button btn = (Button)sender;
               var itemAndPrice = btn.Text;

               int sno = dataGridView1.Rows.Count + 1;
               string nazivartikla = itemAndPrice.Split('-')[0].ToString();
               double cijena = Convert.ToDouble(itemAndPrice.Split('-')[1].ToString());
               string exists = "";
               NazivArtiklaTextBox.Text = nazivartikla;
               Provjera_stanja();
               Sifra_i_Podgrupa_robe();

               foreach (DataGridViewRow g1 in dataGridView1.Rows)
               {
                   if (g1.Cells[2].Value.ToString().Trim() == itemAndPrice.Split('-')[0].ToString().Trim())
                   {
                       exists = "y";
                       g1.Cells[3].Value = Convert.ToInt32(g1.Cells[3].Value) + 1;
                       g1.Cells[5].Value = Convert.ToDouble(g1.Cells[3].Value) * Convert.ToDouble(g1.Cells[4].Value);
                   }
               }

               if (exists != "y")
               {
                   dataGridView1.Rows.Add(sno, SifraTextBox.Text, nazivartikla, 1, cijena, cijena);
               }

               double[] columnData = new double[dataGridView1.Rows.Count];
               columnData = (from DataGridViewRow row in dataGridView1.Rows
                             where row.Cells["kolicina"].FormattedValue.ToString() != string.Empty
                             select Convert.ToDouble(row.Cells["kolicina"].FormattedValue)).ToArray();
               kolicinalabel.Text = columnData.Sum().ToString("0.00");

               double[] columnData2 = new double[dataGridView1.Rows.Count];
               columnData2 = (from DataGridViewRow row in dataGridView1.Rows
                              where row.Cells["ukupno"].FormattedValue.ToString() != string.Empty
                              select Convert.ToDouble(row.Cells["ukupno"].FormattedValue)).ToArray();
               ukupnolabel.Text = columnData2.Sum().ToString("0.00");
               UkupnobezpdvLabel.Text = columnData2.Sum().ToString("0.00");
               label15.Text = columnData2.Sum().ToString("0.00");


               double ukupno;
               if (!double.TryParse(ukupnolabel.Text, out ukupno))
               {
                   // ... report problem to user ...
                   return;
               }
               double lab3;
               if (!double.TryParse(label3.Text, out lab3))
               {
                   //... report problem to user ...
                   return;
               }
               label4.Text = (ukupno * lab3 / 100.0).ToString("0.00");


               dataGridView1.Refresh();


What I have tried:

my code for control button in line  button.Click += new EventHandler(this.btn_Click); call button click function but not work


private void TopliNapitciButton_Click(object sender, EventArgs e)
        {
            panel1.Controls.Clear();

            string conString = ConnectionClass.PullData(labelgodina.Text);
            SqlConnection con = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand("SELECT naziv, FORMAT(cijena_sa_porezom, 'N2') AS cijena, data FROM dbo.roba_usluge where grupa_artikala='Napitci' and status='Aktivan'", con);
            // SqlCommand cmd = new SqlCommand("SELECT naziv+' - '+CAST(FORMAT(cijena_sa_porezom, 'N2') AS varchar), data FROM dbo.roba_usluge where grupa_artikala='Napitci' and status='Aktivan'", con);

            var da = new SqlDataAdapter(cmd);
            var ItemTable = new DataTable();
            da.Fill(ItemTable);

            con.Open();
            Int32 count = ItemTable.Rows.Count;
            con.Close();

            int top = 270;
            int left = 8;
            for (int i = 0; i < count; i++)
            {
                int currentIndex = i;

                Button button = new Button();
                button.Size = new Size(153, 200);
                button.BackColor = Color.Transparent;
                button.FlatAppearance.BorderSize = 0;
                button.Font = new System.Drawing.Font("Roboto", 10);
                button.TextAlign = ContentAlignment.BottomCenter;
                button.BackgroundImageLayout = ImageLayout.Zoom;

                // Create TableLayoutPanel
                TableLayoutPanel table = new TableLayoutPanel();
                table.Dock = DockStyle.Fill;
                table.RowCount = 3;
                table.RowStyles.Add(new RowStyle(SizeType.Percent, 70F));
                table.RowStyles.Add(new RowStyle(SizeType.Percent, 18F));
                table.RowStyles.Add(new RowStyle(SizeType.Percent, 12F));

                // Image
                PictureBox pictureBox = new PictureBox();
                pictureBox.Dock = DockStyle.Fill;
                pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBox.BackColor = Color.FromArgb(63, 77, 103);
                //pictureBox.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, pictureBox.Width, pictureBox.Height, 1, 1));

                if (ItemTable.Rows[i]["data"] != DBNull.Value)
                {
                    byte[] _byte = (byte[])ItemTable.Rows[i]["data"];
                    MemoryStream ms = new MemoryStream(_byte);
                    pictureBox.Image = Image.FromStream(ms);
                }
                else
                {
                    // If the image data is null, assign a default image
                    pictureBox.Image = Properties.Resources.Empty2024x32;
                    pictureBox.SizeMode = PictureBoxSizeMode.CenterImage;
                }

                // Label for name
                Label nameLabel = new Label();
                nameLabel.Dock = DockStyle.Fill;
                nameLabel.TextAlign = ContentAlignment.MiddleCenter;
                nameLabel.Font = new System.Drawing.Font("Roboto", 12, FontStyle.Bold);
                nameLabel.ForeColor = System.Drawing.Color.White;  //Bilo GRAY
                nameLabel.BackColor = System.Drawing.Color.FromArgb(63, 77, 103);
                nameLabel.Text = ItemTable.Rows[i]["naziv"].ToString();

                // Label for price
                Label priceLabel = new Label();
                priceLabel.Dock = DockStyle.Fill;
                priceLabel.TextAlign = ContentAlignment.MiddleCenter;
                priceLabel.ForeColor = System.Drawing.Color.DarkOrange;
                priceLabel.Font = new System.Drawing.Font("Roboto", 14, FontStyle.Bold);
                priceLabel.BackColor = System.Drawing.Color.FromArgb(63, 77, 103);
                priceLabel.Text = ItemTable.Rows[i]["cijena"].ToString() + " KM";

                // Add controls to TableLayoutPanel
                table.Controls.Add(pictureBox, 0, 0);
                table.Controls.Add(nameLabel, 0, 1);
                table.Controls.Add(priceLabel, 0, 2);

                button.Left = left;
                button.Top = top;

                // Add TableLayoutPanel to button
                button.Controls.Add(table);
                panel1.Controls.Add(button);



                pictureBox.Click += (s, ev) =>
                {
                    // Access the captured currentIndex instead of i
                    string itemName = ItemTable.Rows[currentIndex]["naziv"].ToString();
                    string itemPrice = ItemTable.Rows[currentIndex]["cijena"].ToString();

                    // Insert into DataGridView
                    int sno = dataGridView1.Rows.Count + 1;
                    string nazivartikla = itemName;
                    double cijena = Convert.ToDouble(itemPrice.Replace(" KM", ""));
                    string exists = "";
                    NazivArtiklaTextBox.Text = nazivartikla;
                    Sifra_i_Podgrupa_robe();
                    Provjera_stanja();

                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (row.Cells[2].Value != null && row.Cells[2].Value.ToString().Trim() == nazivartikla)
                        {
                            exists = "y";
                            row.Cells[3].Value = Convert.ToInt32(row.Cells[3].Value) + 1;
                            row.Cells[5].Value = Convert.ToDouble(row.Cells[3].Value) * Convert.ToDouble(row.Cells[4].Value);
                            break; // Exit loop once found
                        }
                    }

                    if (exists != "y")
                    {
                        dataGridView1.Rows.Add(sno, SifraTextBox.Text, nazivartikla, 1, cijena, cijena);
                    }

                    button.Click += new EventHandler(this.btn_Click);

                    dataGridView1.Refresh();
                };


                if ((i + 1) % 5 == 0)
                {
                    left = 8;
                    top += button.Height + 2;
                }
                else
                {
                    left += button.Width + 2;
                }
            }
        }
Posted
Comments
Ralf Meier 9-Apr-24 3:05am    
Without seeing what your Debugger "says" I suppose that the assignment to the Eventhandler isn't realized at the right point.
I suggest that you don't do it manually and assign it with the Designer - so it will be established with the Form call.
Why have you coded it inside the TopliNapitciButton_Click-method ?

Set a debug breakpoint on the line: button.Click += new EventHandler(this.btn_Click); and make sure that the line is being hit. If it is, the app will pause on that line.
 
Share this answer
 
I'm confused as to what your problem actually is here. In this part, are you saying you are trying to use this code to hook up to the click event?
my code for control button in line  button.Click += new EventHandler(this.btn_Click); call button click function but not work
If it is, it's no wonder your code isn't compiling/working. You want to be using this
C#
TopliNapitciButton.Click += TopliNapitciButton_Click;
While you are looking at your code, you have a lot of resources in there that you should be disposing that you aren't, and these are things that will end up causing unintentional side-effects. For instance, you have a SqlCommand and SqlConnection; these should both be disposed. Have a look through your code at the other things you are using that should be disposed of, and wrap them in using blocks to free them up.
 
Share this answer
 
That's some odd code - you only add the button Click event handler if the picture box is clicked:
C#
                button.Controls.Add(table);
                panel1.Controls.Add(button);



                pictureBox.Click += (s, ev) =>
                {
                    // Access the captured currentIndex instead of i
...
                    button.Click += new EventHandler(this.btn_Click);

                    dataGridView1.Refresh();
                };
But to be honest, adding a TableLayoutPanel to your Button.Controls array is probably what prevents the click event happening at all as the table will probably "steal" the Click event for itself ...
I've never seen a Button being used as a Container, and it's probably not a good idea!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900