How to write dynamic pictureBox Click event in C#? - c#

private void button1_Click(object sender, EventArgs e)
{
PictureBox dynamicPicture1 = new PictureBox();
dynamicPicture1.Tag = i;
dynamicPicture1.Location = new Point(x, y);
dynamicPicture1.Name = "pictureBox" + i;
dynamicPicture1.Size = new System.Drawing.Size(30, 27);
dynamicPicture1.ImageLocation =
"C:\\Users\\Newfolder\\Downloads\\x`enter code here`ryrvc.jpg";
panel1.Controls.Add(dynamicPicture1);
}

Try this updated code.
private void button1_Click(object sender, EventArgs e)
{
int s = 4;
int x = 0;
int y = 0;
for (int i = 0; i < s; i++)
{
if (i == 0)
{
x = 38;
y = 60;
}
else
{
y += 50;
}
PictureBox dynamicPicture1 = new PictureBox();
dynamicPicture1.Tag = i;
dynamicPicture1.Location = new Point(x, y);
dynamicPicture1.Name = "pictureBox" + i;
dynamicPicture1.Size = new System.Drawing.Size(30, 27);
dynamicPicture1.ImageLocation = #"C:\Users\nxa00960\Downloads\abc.jpg";
panel1.Controls.Add(dynamicPicture1);
dynamicPicture1.Click += dynamicPicture1_Click;
}
}
void dynamicPicture1_Click(object sender, EventArgs e)
{
var pictureBox = sender as PictureBox;
switch (pictureBox.Name)
{
case "pictureBox0":
//do something
break;
case "pictureBox1":
//do something
break;
case "pictureBox2":
//do something
break;
case "pictureBox3":
//do something
break;
default:
break;
}
}

You should put the Method name of your event handler:
dynamicPicture1.Click += dynamicPicture1_Click; //note the name here
And define the event handler somewhere:
void dynamicPicture1_Click(object sender, EventArgs e) {
throw new NotImplementedException(); //default not implemented
}
The name of the event handler must match each other...

Related

Add Events To Dynamically added Buttons in Winform

I had Added Button Controls dynamically in window form,now i want to add different event to every button control.
Here is my code of adding button dynamically from database.
private void GetButtonDynamically()
{
SqlConnection conn = GetConnection();
conn.Open();
using (conn)
{
SqlCommand cmd = new SqlCommand("Select MenuName from tblMainMenu",conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Button mybutton = new Button();
mybutton.Location = new Point(x, y + 54);
y += 54;
mybutton.Height = 44;
mybutton.Width = 231;
mybutton.BackColor = Color.Gainsboro;
mybutton.ForeColor = Color.Black;
mybutton.Text = reader["MenuName"].ToString();
mybutton.Name = reader["MenuName"].ToString();
mybutton.Font = new Font("Georgia", 12);
Controls.Add(mybutton);
mybutton.Click+= new EventHandler(mybutton_Click);
}
conn.Close();
}
}
Now the problem i am facing is it generate same Event for every button that is created dynamically, and i want different method for every button
Here Is Click Event
private void mybutton_Click(object sender, EventArgs e)
{
MessageBox.Show("Button is Clicked");
}
You can add a "AccessibleName" for your button while creating it. In your case inside your while loop and get the accessible name in button click event and apply a switch case or loop to differentiate it. sample code
int x = 10; int y = 10;
for (int i = 1; i < 5; i++)
{
Button mybutton = new Button();
mybutton.Location = new Point(x, y + 54);
y += 54;
mybutton.Height = 44;
mybutton.Width = 231;
mybutton.BackColor = Color.Gainsboro;
mybutton.ForeColor = Color.Black;
mybutton.Text = i + "MenuName".ToString();
mybutton.Name = i + "MenuName".ToString();
mybutton.AccessibleName = i.ToString();
mybutton.Font = new Font("Georgia", 12);
Controls.Add(mybutton);
mybutton.Click += new EventHandler(mybutton_Click);
}
In Button click modify like this
private void mybutton_Click(object sender, EventArgs e)
{
Button cb = (Button)sender;
string strName = cb.AccessibleName;
switch (strName)
{
case "1":
MessageBox.Show("Button 1 is Clicked");
break;
case "2":
MessageBox.Show("Button 2 is Clicked");
break;
case "3":
MessageBox.Show("Button 3 is Clicked");
break;
default:
break;
}
}
I think it can help you:
private void Form1_Load(object sender, EventArgs e)
{
int y = 0;
for (int i = 0; i < 10; i++)
{
Button mybutton = new Button();
mybutton.Location = new Point(0, y + 10);
y += 54;
mybutton.Height = 44;
mybutton.Width = 231;
mybutton.BackColor = Color.Gainsboro;
mybutton.ForeColor = Color.Black;
mybutton.Text = "a "+i.ToString();
mybutton.Name = "b" + i.ToString();
mybutton.Font = new Font("Georgia", 12);
switch (i)// define your condition
{
case 1:
mybutton.Click += new EventHandler(mybutton_Click);
break;
case 2:
mybutton.Click += new EventHandler(mybutton_1_Click);
break;
default:
break;
}
Controls.Add(mybutton);
}
}
private void mybutton_Click(object sender, EventArgs e)
{
MessageBox.Show("Button 1 is Clicked");
}
private void mybutton_1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button 2 is Clicked");
}

Memory game, PictureBox im1 = sender as PictureBox; loses it's address

I'm trying to make a basic memory game for now in C#, I'm using sender as PictureBox to determine min which picture box is selected.After that I have to check if the tags are equal, and here im2 and im1 loses its address. How can I save the addresses so they don't get loss?
public partial class Form1 : Form
{
int k = 1;
PictureBox im1, im2;
int r1, r2;
public Form1()
{
InitializeComponent();
}
private void Click(object sender, EventArgs e)
{
if (k == 1)
{
PictureBox im1 = sender as PictureBox;`enter code here`
r1 = Convert.ToInt16(im1.Tag);
string s = "slike\\sl";
s = s + r1.ToString() + ".jpg";
Image i = Image.FromFile(#s);
im1.Image = i;
k = 2;
}
else
{
PictureBox im2 = sender as PictureBox;
r2 = Convert.ToInt16(im2.Tag);
string s = "slike\\sl";
s = s + r2.ToString() + ".jpg";
Image i = Image.FromFile(#s);
im2.Image = i;
k = 0;
}
if(k==0) {
if (r1 == r2)
{
Image i = Image.FromFile(#"slike\\pogodjeno.jpg");
im1.Image = i;
im2.Image = i;
im1.Enabled = false;
im2.Enabled = false;
k = 1;
}
else
{
Image i = Image.FromFile(#"slike\\pozadina.jpg");
im1.Image = i;
im2.Image = i;
r1 = 0;
r2 = 0;
k = 1;
}
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
This doesn't seem right:
PictureBox im1, im2;
private void Click(object sender, EventArgs e)
{
PictureBox im1 = sender as PictureBox;`enter code here`
You probably want this:
private void Click(object sender, EventArgs e)
{
im1 = sender as PictureBox;`enter code here`

C# How to make PictureBoxs move automatically?

I created 5 PictureBox "Shapes" and I want them to move to the left automatically when the program is launched. So in the timer1_Tick method, I use "Shapes[i].Left -= 2", it's said that "Shapes" isn't in the actual context, so How can I make the Shapes[i] global from the "CreatePipes" method?
public partial class Form1 : Form
{
int i = 0;
int N = 5;
int yspeed;
int gravity = 2;
public Form1()
{
InitializeComponent();
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
yspeed = -15;
}
}
private void Form1_Load(object sender, EventArgs e)
{
CreatePipes(1);
}
public void CreatePipes(object Number)
{
PictureBox[] Shapes = new PictureBox[N];
for (i = 0; i < N; i++)
{
Shapes[i] = new PictureBox();
Shapes[i].Name = "ItemNum_" + i.ToString();
Shapes[i].Location = new Point(300 + 120 * i, 250);
Shapes[i].Size = new Size(30, 1000 );
Shapes[i].BackColor = Color.Green;
Shapes[i].Visible = true;
this.Controls.Add(Shapes[i]);
}
}
private void bird_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
for (i = 0; i < N; i++)
{
Shapes[i].Left -= 2; //So the problem is here. Shapes[i] isn't in the actual context. But I don't know to to make it global from CreatePipes
}
yspeed += gravity;
bird.Top += yspeed;
}
}
}
You have to declare PictureBox[] Shapes above CreatePipes function, in Form1 class. Then in CreatePipes func, change PictureBox[] Shapes = new PictureBox[N]; to Shapes = new PictureBox[N];

Adding Event Handler for Dynamically Created to window Form

I have a window form where I am creating a list of Checkboxes. The number of checkboxes created are based upon how many items are returned from the database. I've been able to create the checkboxes; however, I am not sure how to add event handlers for these checkboxes. For example, I'd like to add an OnCheckedChanged or CheckStateChanged event. How can I add these events? Also, I would appreciate any other suggestion. I am a total newbie to programming.
private void Form1_Load(object sender, EventArgs e)
{
CheckBoxes = new CheckBox[listGroup.Count()];
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i]+"_CheckedChanged");
CheckBoxes[i].Width = 200;
if (i == 0)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 10);
}
else if (i == 1)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 40);
}
else if (i == 2)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 80);
}
this.Controls.Add(CheckBoxes[i]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//...
CheckBoxes[i].CheckedChanged += checkBoxes_CheckedChanged;
CheckBoxes[i].CheckStateChanged += checkBoxes_CheckStateChanged;
}
void checkBoxes_CheckedChanged(object sender, EventArgs e)
{ //do stuff when checked changed }
void checkBoxes_CheckStateChanged(object sender, EventArgs e)
{ //do stuff when check state changed }
Note: this will give identical event handling for all of your checkboxes.
If you want to do different things for different textboxes, you have to name the eventhandler differently and define that eventhandler.
A more efficient way to set the location of your checkboxes
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i] + "_CheckedChanged");
CheckBoxes[i].Width = 200;
//set location based on index of i
CheckBoxes[i].Location = new System.Drawing.Point(5, 10 + (i * 30));
this.Controls.Add(CheckBoxes[i]);
}
private void LoadNewCheckboxes()
{
dynamic listGroupCount = 10;
List<System.Windows.Forms.CheckBox> CheckBoxes = new List<System.Windows.Forms.CheckBox>();
for (int i = 0; i <= listGroupCount - 1; i++)
{
System.Windows.Forms.CheckBox chkbox = new System.Windows.Forms.CheckBox();
chkbox.Text = i.ToString();
//listGroup.ElementAt(i).GroupName
chkbox.Name = "txt" + i.ToString();
//listGroup.ElementAt(i).GroupName.Replace(" "c, "_"c)
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox.CheckStateChanged += new EventHandler(chkbox_CheckStateChanged);
chkbox.Width = 200;
chkbox.AutoSize = true;
this.Controls.Add(chkbox);
CheckBoxes.Add(chkbox);
if (i == 0)
{
chkbox.Location = new System.Drawing.Point(5, 10);
}
else
{
chkbox.Location = new System.Drawing.Point(5, (CheckBoxes[i - 1].Top + CheckBoxes[i - 1].Height + 10));
}
}
}
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckedChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}
private void chkbox_CheckStateChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckStateChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}

C# - Click event sending a value

I'm using a for-loop to add values into an array of PictureBox and binding a click event to each one. I'm looking for a way of getting the data of a PictureBox after clicking on it. Since it's an array, I was thinking of sending the value of the loop counter, which would identify which one was clicked.
My code looks like this:
PictureBox[] picboxes = new PictureBox[result];
for (int i = 0; i < results; i++)
{
picboxes[i] = new PictureBox();
picboxes[i].ImageLocation = #FormIni.RetRes((i * 5) + 5 + i);
picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);
}
private void PictureBoxes_Click(object sender, EventArgs e)
{
label1.Text = "here I need the value of the picboxes[i] image location";
}
It can seem stupid, but I thought of something like:
picboxes[i].Click += new System.EventHandler(PictureBoxes_Click(i))
and
private void PictureBoxes_Click(object sender, EventArgs e, int i)
In short: when I click in a PictureBox created in a array via code, how do I get its values (inside the click event handler)?
EDIT!
Sorry for finding it only after making this question, but I've found this solution and it may apply to my case, right?
try do do this
PictureBox[] picboxes = new PictureBox[result];
for (int i = 0; i < results; i++)
{
picboxes[i] = new PictureBox();
picboxes[i].Name = (i+1).ToString();
picboxes[i].ImageLocation = #FormIni.RetRes((i * 5) + 5 + i);
picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);
}
private void PictureBoxes_Click(object sender, EventArgs e)
{
PictureBox p = (PictureBox)sender;
string j = p.Name;
label1.Text = j;
}
You can use the following (anoynomous method) lambda expression
picboxes[i].Click += (sender, eventArguments) => PictureBoxes_Click(sender, eventArguments, i);
Use Tag
PictureBox[] picboxes = new PictureBox[result];
for (int i = 0; i < results; i++)
{
picboxes[i] = new PictureBox();
picboxes[i].Tag = (i+1).ToString();
picboxes[i].ImageLocation = #FormIni.RetRes((i * 5) + 5 + i);
picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);
}
private void PictureBoxes_Click(object sender, EventArgs e)
{
PictureBox p = (PictureBox)sender;
string j = p.tag.tostring();
label1.Text = j;
}

Categories

Resources