I'm creating a radio button in C# code for a WinRT application.
My code:
for(var l = 0; l < 4; l++) {
RadioButton radio = new RadioButton();
radio.Checked += (sender,arg)=>{ //sender };
stackpanel.children.add(radio);
}
Now I add those radio buttons in page and I need to know which radio button is checked but when event fires it's sent to me only the last button. How do I make an event for every button so that when someone checks Button 1 I can send a message box: "you checked button 1"?
Use the CheckChangedEvent. Try to use this in your for-loop:
RadioButton radio = new RadioButton();
radio.Name = "Button" + l;
radio.CheckedChanged += Radio_CheckedChanged;
And then when the event is triggered do the following:
/// <summary>
/// This will trigger all changes to the CheckedState - even unchecking
/// </summary>
private void Radio_CheckedChanged(object sender, EventArgs e)
{
RadioButton checkedRadioButton = (RadioButton) sender;//Cast the sender of the event back to RadioButton
if (checkedRadioButton.Checked)//Only do this when checking - not on unchecking
{
MessageBox.Show($"You checked {checkedRadioButton.Name}", "Pressed");
}
}
Related
I have a number of radio buttons created dynamically inside a loop and added to a div inside update panel. On each postback request triggered by checked change event, I recreate the radio buttons in my page_init method. My problem is the radio button I selected is not checked and the checked changed event is not firing on first click. But on subsequent clicks, it works normally and the checked changed event is fired. Only the first click is not firing. What could be the issue?
Simple dynamic radio button.
RadioButton btn2 = new RadioButton();
btn2.Text = "TEST";
btn2.CheckedChanged += Btn2_CheckedChanged; ;
btn2.AutoPostBack = true;
pricetbldiv.Controls.Add(btn2);
private void Btn2_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = (RadioButton)sender;
string text = btn.Text;
}
Try to assign group and ID
btn2.ID = "Text";
btn2.Text = "Text";
btn2.GroupName = "RB";
btn2.CheckedChanged += new EventHandler(Btn2_CheckedChanged);
I'm creating the radio buttons in the ContextMenuStrip using the ToolStripControlHost, this way
RadioButton taskRb = new RadioButton();
taskRb.Text = DataGridTable.getTasks()[i].name.ToString();
taskRb.Checked = false;
ToolStripControlHost tRb = new ToolStripControlHost(taskRb);
contextMenuStrip2.Items.Add(tRb);
I need an event like CheckedChanged for the radio buttons in this list, so I can perform some actions when one of the buttons is checked.
What is the best way to do this? since I can't use this event with the ToolStripControlHost.
You can register an event handler for the CheckedChanged event of the RadioButton:
RadioButton taskRb = new RadioButton();
taskRb.CheckedChanged += new EventHandler(taskRb_CheckedChanged);
taskRb.Text = DataGridTable.getTasks()[i].name.ToString();
taskRb.Checked = false;
ToolStripControlHost tRb = new ToolStripControlHost(taskRb);
contextMenuStrip2.Items.Add(tRb);
protected void taskRb_CheckedChanged(object sender, EventArgs e)
{
// Do stuff
}
I'm creating buttons dynamically. How can I select a specific button using its name (ex: in the following code using "i" ) from remaining part of the code.
for(int i = 0; i < 5; i++)
{
button b = new button();
b.name = i.ToString();
}
First - its not enough to just create buttons. You need to add them to some control:
for(int i = 0; i < 5; i++)
{
Button button = new Button();
button.Name = String.Format("button{0}", i); // use better names
// subscribe to Click event otherwise button is useless
button.Click = Button_Click;
Controls.Add(button); // add to form's controls
}
Now you can search child controls of buttons container for some specific button:
var button = Controls.OfType<Button>().FirstOrDefault(b => b.Name == "button2");
NOTE: If you'll use buttonN name pattern then make sure you don't have other buttons with same names, because this pattern is used by VS designer.
UPDATE: If you will use same event handler for all dynamic buttons Click event (actually you should), then you can easily get button which raised even in event handler:
private void Button_Click(object sender, EventArgs e)
{
// that's the button which was clicked
Button button = (Button)sender;
// use it
}
A simpler solution is search the button in the Controls collection.
Button btn = (Button) this.Controls["nameButton"];
//...DO Something
The problem of this solution is that if there isn't a button with the nameButton the JIT will throw an exception. If you want prevent this you must insert the code in a try catch block or, if you prefer, you can use Sergey Berezovskiy solution(he uses Linq and I think it's more clear)
You have to place your button somewhere:
for (int i = 0; i < 5; i++) {
// Mind the case: Button, not button
Button b = new Button();
// // Mind the case: Name, not name
b.Name = i.ToString();
//TODO: place your buttons somewhere:
// on a panel
// myPanel.Controls.Add(b);
// on a form
// this.Controls.Add(b);
// etc.
//TODO: it seems, that you want to add Click event, something like
// b.Click += MyButtonClick;
}
then you can just query appropriate Controls for the Button:
Button b = myPanel.Controls["1"] as Button;
if (b != null) {
// The Button is found ...
}
You could just put them in a Button[] or you could iterate over the Controls collection of your Form.
I've got an event handler that is shared by all of my radiobuttons:
private void radioButtonPackers_CheckedChanged(object sender, EventArgs e)
{
var rb = sender as RadioButton;
if (rb == radioButtonPackers)
{
team = NFCNorth.Packers;
} else if (rb == radioButtonBears)
{
team = NFCNorth.Bears;
} else if . . .
}
rb is always seen as being radioButtonPackers, even after I've checked the radioButtonBears, radioButtonVikings, or radioButtonLions radiobutton.
Do I have to do something like:
if (radioButtonPackers.Checked)
{
team = NFCNorth.Packers;
}
else if (radioButtonBears.Checked)
{
team = NFCNorth.Bears;
}
. . .
?
It doesn't work in that way, actually. It has to receive like a sender any radiobutton clicked. Your confusion may be related to a fact that radioButtonPackers_CheckedChanged you can recieve twice, in case if radiobuttons are grouped, so when one is clicked the current one
first becomes unchecked (so raise event)
after comes event of a "new" radiobutton
You need to take note of rb.Checked, but in my experience you'll get an "unchecked" event before you get the "checked" one anyway. Here's a short but complete example which works:
using System;
using System.Windows.Forms;
class Program
{
public static void Main()
{
var b1 = new RadioButton { Text = "Button 1" };
var b2 = new RadioButton { Text = "Button 2" };
EventHandler handler = (sender, args) => {
RadioButton button = (RadioButton) sender;
Console.WriteLine("{0} {1}",
button.Text,
button.Checked ? "Checked" : "Unchecked");
};
b1.CheckedChanged += handler;
b2.CheckedChanged += handler;
var form = new Form {
Controls = {
new FlowLayoutPanel {
FlowDirection = FlowDirection.TopDown,
Controls = { b1, b2 }
}
}
};
Application.Run(form);
}
}
If you click on Button 1 then on Button 2, you'll see:
Button 1 Checked
Button 1 Unchecked
Button 2 Checked
Yes, you need to look at the .Checked property.
The first time you click one of the radio buttons, a single CheckedChanged event is fired (for turning "on" the button). Then, when you click a different radio button in the same group, there are two CheckedChanged events that are fired, one for the unchecking of the first radio button, and the other for the checking of the second.
http://msdn.microsoft.com/en-us/library/system.windows.forms.radiobutton.checkedchanged.aspx
My guess is your code is working correctly but you're seeing the CheckedChanged event being fired for the previously selected RadioButton when it changes from being checked to unchecked, before the just selected RadioButton gets its check (and the event fires for it).
I created a page where I give admin's a way to change photos info (e.g. Title, Description, etc) All the controls on the page are added dynamically because I have more than one gallery of photos.
panel --> parent.
button .
title text box.
description text box.
In every panel, I have button that when clicked, sends the changed information to the server where the photo info is stored (Flickr). The click event for this button is added dynamically, and I want to know if is possible to get the parent of the Button I just clicked on.
Here is the code where I add all my controls:
//global veriables (this is only part of the code)
Panel panel;
Button button;
for (int i = 0; i < photo.Length; i++) {
photo[i] = new FlickerImages(photoSet.MediumURLS[i], photoSet.ThumbnailURLS[i], photoSet.Titles[i], photoSet.Descreption[i]);
panel = new Panel();
panel.ID = "panel" + i;
button = new Button();
button.ID = "sendDataButton" + i;
button.Text = "send data";
button.Click += button_Click; //adding the event
label = new Label();
label.ID = "editLabel" + i;
panel.Controls.Add(label);
panel.Controls.Add(photo[i].CurrentImage(i)); //Image control
panel.Controls.Add(photo[i].EditTitleTextBox(i)); //TextBox control
panel.Controls.Add(photo[i].EditCommentTextBox(i)); //TextBox control
panel.Controls.Add(button);
Form.Controls.Add(panel);
}
Here is the click event I add to all the buttons:
void button_Click(object obj, EventArgs e) {
Response.Write(button.Parent.ID); // i get panel10 every time this get fired.
}
I know this is possible with jQuery but is it possible to get the button ID in ASP.NET?
Sorry for my English and thanks for the help.
Not sure, but are you looking for the ClientID property? (button.Parent.ClientID)
Edit:
You should reference the sending button in the event handler:
void button_Click(object obj, EventArgs e)
{
Response.Write(((Button)obj).Parent.ID);
}