I have created an Array of UserControls which have 1 PictureBox and 1 Button. Now I want to know which Button is pressed from the Array of UserControl.
UserControl u=new UserControl[20];
for (int j = 0; j < 20; j++)
{
u[j] = new UserControl();
u[j].BringToFront();
flowLayoutPanel1.Controls.Add(u[j]);
u[j].Visible = true;
u[j].button1.Click+=new EventHandler(sad);
}
private void sad(object sender, EventArgs e)
{
//how to determine which button from the array of usercontrol is pressed?
}
The sender parameter contains the Control instance that generated the event.
something like this:
private void sad(object sender, EventArgs e) {
var buttonIndex = Array.IndexOf(u, sender);
}
This should do close to what you want. I can modify as needed to suit your case.
FlowLayoutPanel flowLayoutPanel1 = new FlowLayoutPanel();
void LoadControls()
{
UserControl[] u= new UserControl[20];
for (int j = 0; j < 20; j++)
{
u[j] = new UserControl();
u[j].BringToFront();
flowLayoutPanel1.Controls.Add(u[j]);
u[j].Visible = true;
u[j].button1.Click +=new EventHandler(sad);
}
}
private void sad(object sender, EventArgs e)
{
Control c = (Control)sender;
//returns the parent Control of the sender button
//Could be useful
UserControl parent = (UserControl)c.Parent; //Cast to appropriate type
//Check if is a button
if (c.GetType() == typeof(Button))
{
if (c.Name == <nameofSomeControl>) // Returns name of control if needed for checking
{
//Do Something
}
}
//Check if is a Picturebox
else if (c.GetType() == typeof(PictureBox))
{
}
//etc. etc. etc
}
I think this gets you what you want:
if (sender is UserControl)
{
UserControl u = sender as UserControl();
Control buttonControl = u.Controls["The Button Name"];
Button button = buttonControl as Button;
}
Related
My code makes 5 labels appear with a random .Left location, you can see it.
I want the particular label to disappear when I click on it, but I don't know how to tell it to my click void.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Label [] kubeliai = new Label [5];
int poz = 100;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < kubeliai.Length; i++)
{
kubeliai[i] = new Label();
Controls.Add(kubeliai[i]);
Random pos = new Random();
kubeliai[i].Top = 50;
kubeliai[i].Left = poz;
poz += pos.Next(50, 200);
kubeliai[i].BackColor = Color.Red;
kubeliai[i].Height = 20;
kubeliai[i].Width = 20;
kubeliai[i].Click += new EventHandler(kubelio_clickas);
}
}
void kubelio_clickas (object sender, EventArgs e)
{
}
}
The instance of "clicked" label is in sender parameter:
void kubelio_clickas (object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (clickedLabel != null) {
clickedLabel.Visible = false;
}
}
Because in .NET Event Handlers by default use object as type of sender you have to cast it to Label first.
I want the particular label to disappear when I click on it
Just set the label's .Visible property to false:
void kubelio_clickas (object sender, EventArgs e)
{
if (sender is Label)
((Label)sender).Visible = false;
}
The object sender is a reference to the object which fired the event. So basically, the sender is the object you are looking for.
You just need to set it invisible:
((Label)sender).Visible = false;
i dynamically create several picture box, and EventHandler. when user click on pictureBox, the program should delete tрis item. (the item that the user selected)
i try do
for (int i = 1; i <= sunduki; i++)
{
PictureBox PBObj = new PictureBox();
PBObj.Location = new System.Drawing.Point(i * 100, 101);
PBObj.Name = "pictureBox" + i.ToString();
PBObj.Size = new System.Drawing.Size(108, 80);
PBObj.TabIndex = i;
PBObj.BackgroundImage = Image.FromFile(#"syndyk1.jpg");
PBObj.BackgroundImageLayout = ImageLayout.Zoom;
PBObj.Click += new System.EventHandler(pb_Click);
PB.Add(PBObj);
Controls.Add(PB[PB.Count - 1]);}
and in pb_click
private void pb_Click(object sender, EventArgs e)
{ PB[this].Visible = false; }
but i have an error. (PB is the list with pictureBox)
The sender argument will be the object that has been clicked, in this case it is the PictureBox object.
private void pb_Click(object sender, EventArgs e)
{
var pb = sender as PictureBox;
if(pb != null)
{
pb.Visible = false;
}
}
Note: This doesn't delete the picture box, but makes it not visible. Controls deletion is handled by the disposal of the form.
Hi all I am creating some button dynamically, and when user click on the button I need to set the BackColor for the selected button to some highlighted color, as per the code what I have written it is applying color for every button, instead of that I need to apply color for the user clicked button
My code for creating buttons is as follows
for(int i=0;i<5;i++)
{
Button btyDynamic = new Button();
btyDynamic .Click += new EventHandler(btyDynamic _Click);
btyDynamic .AutoSizeMode = AutoSizeMode.GrowAndShrink;
btyDynamic .AutoSize = true;
btyDynamic .Text = i.ToString();
btyDynamic .Tag = i.ToString();;
}
protected void btyDynamic(object sender, EventArgs e)
{
Button btn= sender as Button;
string strTag= btn.Tag.ToString();
switch(strTag)
{
case "0":
btn.BackColor=Color.LightSteelBlue;
break;
// Like this I am writing, now when in Case2 I need to remove the color of the first button and to show the backcolor of second button
}
}
You could store the last button selected and then reset the BackColor:
private Button _lastButtonSelected = null;
protected void btyDynamic(object sender, EventArgs e)
{
// Set new button back color
Button btn = sender as Button;
if(btn != null)
{
btn.BackColor = Color.LightSteelBlue;
}
// Reset last button color
if(_lastButtonSelected != null)
{
_lastButtonSelected.BackColor = ...; // Put default back color here
}
_lastButtonSelected = btn;
}
If you want the BackColor to remain LightSteelBlue if you click the same button twice, you just need to check that the _lastButtonSelected != btn as well.
you could make a foreach for all buttons, and remove background for all button not equal to sender. Suppose to save all buttons into an array (_AllButtons). you could write some code like this:
Button btn= sender as Button;
foreach(var currentButton in _AllButtons) {
if(currentButton !=btn) {
currentButton.BackColor=Color.Transparent;
}
}
A possible algorithm would be:
create the buttons once as you already do and bind the click event to one handler
in the click handler first reset all buttons to the standard background color
in the click handler find the currently clicked button using switch as you already do and set the color of this button
Sample code:
Action resetButtonColor = () =>
{
button1.BackColor = Colors.Red;
button2.BackColor = Colors.Red
button3.BackColor = Colors.Red;
};
resetButtonColor();
var selected = Colors.Green;
switch(strTag)
{
case "1": button1.BackColor = selected;
case "2": button2.BackColor = selected;
case "3": button3.BackColor = selected;
}
Then You must assign to the click event of this one button explicetely.
All others could have this handler, but the one button should not, because it is too generic handled in this way.
You can try this:
Color highLite = Color.Black;
public Form1()
{
InitializeComponent();
for (int i = 0; i < 20; i++)
{
Button b = new Button();
b.Text = i.ToString();
b.Tag = null;
b.Click += b_Click;
flowLayoutPanel1.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
b.BackColor = highLite;
// clear backcolors
foreach (Control c in flowLayoutPanel1.Controls)
if (c != b)
c.BackColor = SystemColors.Control;
}
Make sure you are only setting backcolors of controls you want to set. Make the tag have something unique to tell you that you want to change it.
private Color offColor = Color.Red;
private Color onColor = Color.Blue;
private String btyPrefix = "bty";
private void btyDynamic_click(object sender, EventArgs e)
{
Control control = (Control)sender;
// enumerate this.Controls, but if they go into a different container, enumerate over that
this.Controls.OfType<Control>()
.Where(c => ((String)c.Tag).Contains(btyPrefix))
.ToList<Control>()
.ForEach(c =>
{
if (control == c)
c.BackColor = onColor;
else
c.BackColor = offColor;
}
);
}
private void Form1_Load(object sender, EventArgs e)
{
Button btyDontChange = new Button();
btyDontChange.AutoSize = true;
btyDontChange.AutoSizeMode = AutoSizeMode.GrowAndShrink;
btyDontChange.Text = "x";
btyDontChange.Tag = "something";
btyDontChange.Location = new Point(0, 0);
this.Controls.Add(btyDontChange);
for (int i = 0; i < 5; i++)
{
Button btyDynamic = new Button();
btyDynamic.Click += new EventHandler(btyDynamic_click);
btyDynamic.AutoSizeMode = AutoSizeMode.GrowAndShrink;
btyDynamic.AutoSize = true;
btyDynamic.Text = i.ToString();
btyDynamic.Tag = btyPrefix + i.ToString();
btyDynamic.Location = new Point((i+1) * 50, 0);
btyDynamic.BackColor = offColor;
this.Controls.Add(btyDynamic);
}
}
I have 20 radiobuttons on the page and I want to know which one of them was clicked.
protected void Page_Load(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "Button 1";
PlaceHolder1.Controls.Add(newBTN);
for (int i = 0; i < 20; i++)
{
RadioButton r = new RadioButton();
r.ID = i.ToString();
r.CheckedChanged += RadioButton1_CheckedChanged;
PlaceHolder1.Controls.Add(r);
}
}
New Updated code.. NOTE: THE CODE DOESNT RELATE TO THE ABOVE CODE.
public List<int> ThreadID2Treat { get { return ViewState["Checked"] == null ? null : (List<int>)ViewState["Checked"]; } set { ViewState["Checked"] = value; } }
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var rad = (CheckBox)sender;
int threadID = int.Parse(rad.ID.ToString());
ThreadID2Treat.Add(threadID);
}
public void DeleteButton_Clicked(object sender, EventArgs e)
{
foreach (var item in ThreadID2Treat)
{
UsefulStaticMethods.DeleteThreads(item);
}
}
How do i find out?
var rad = (RadioButton)sendder;
Response.Write("RadioButton Id :" + rad.Id.ToString());
You could try the above.
Update :
To get all select radio buttons in PlaceHolder make sure the AutoPostBack is not set on the radio buttons. You dont need to add CheckChanged Event. "r.CheckedChanged += RadioButton1_CheckedChanged;" <= remove.
StringBuilder stringBuilder = new StringBuilder();
foreach (var control in placeHolder1.Controls)
{
var rad = control as RadioButton;
if (rad != null)
{
if (rad.Checked)
stringBuilder.AppendLine(String.Format("Radion Button Checked : {0}", rad.ID));
}
}
Response.Write(stringBuilder.ToString());
With the parameter sender you have a direct reference to the event-source control.
var rb = (RadioButton)sender;
If you want to trigger this event and the postback directly, you must set the RadioButton's AutoPostBack-Property to true.
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (sender is RadioButton)
{
RadioButton radioButton = (RadioButton)sender;
//Code to use radioButton's properties to do something useful.
// get the radio button by its ID
string id = radioButton.ID;
}
}
You can try this.
RadioButton r = sender as RadioButton;
Response.Write(r.Id);
Cast sender as RadioButton:
RadioButton r = sender as RadioButton;
if(r != null)
{
//Do stuff
}
I am developing a project in C# Windows applications (WinForms) in that I need to create a function to change the background color for all the buttons that are in the single form using button mouse-over event. How do I do that?
Changing all controls of type Button:
for (int i = 0; i < Controls.Count; i++)
if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
Example of hooks:
MouseEnter += new EventHandler(delegate(object sender, EventArgs e)
{
SetButtonColour(Color.Blue);
});
MouseLeave += new EventHandler(delegate(object sender, EventArgs e)
{
SetButtonColour(Color.Red);
});
public void SetButtonColour(Color colour)
{
for (int i = 0; i < Controls.Count; i++)
if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
}
Assuming you are just changing your own app, this isn't that difficult.
In the mouse over event, just loop over the Controls property of the form and for all items that are Button, change the back color. You will need to write a recursive function to find all of the buttons probably though, since a Panel (or GroupBox, etc) contains a Controls property for all of its controls.
Something like this:
public partial class Form1 : Form
{
Color defaultColor;
Color hoverColor = Color.Orange;
public Form1()
{
InitializeComponent();
defaultColor = button1.BackColor;
}
private void Form1_MouseHover(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
{
ctrl.BackColor = hoverColor;
}
}
}
private void Form1_MouseLeave(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
{
ctrl.BackColor = defaultColor;
}
}
}
}