Fire RadioButton checked routed event programmatically - c#

Is there anyway to raise a RadioButton checked routed event from code, in order to handle it in a parent control?
This is the situation:
var radio = new RadioButton();
radio.IsChecked = true;
radio.RaiseEvent(new RoutedEventArgs(RadioButton.CheckedEvent));
The third line does not work.
Googling, I found another way based on the RadioButtonAutomationPeer, but I had not found a way to make it work.
Does someone have some hint?
Thanks in advance.

var radio = new RadioButton();
radio.CheckedChanged +=new EventHandler(radio_CheckedChanged);
radio.IsChecked = true;
private void radio_CheckedChanged(object sender, EventArgs e)
{
if (radio.Checked)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}
}

You can get Radio checked event programmatically but not directly add on page/form.
you have to create panel or some else controler in which you can add this Radio Button like this
this is your .aspx page
<div>
<asp:Panel runat="server" ID="pnl1">
</asp:Panel>
</div>
this is your aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
var radio = new RadioButton { Checked = false, AutoPostBack = true, Text = "Click" };
radio.CheckedChanged += radio_CheckedChanged;
pnl1.Controls.Add(radio);
}
void radio_CheckedChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}

Related

How can I invoke a server-side event from jQuery (Sharepoint 2010)?

In my Sharepoint 2010 app, I'm handling most events client-side with jQuery. However, for the saving of data to the Sharepoint list, and the generation of a PDF file with that data, I want to handle that server-side, with C#.
I tried to invoke a C# event this way:
0) Aded an HTML button in my project's *.ascx file:
<button type="button" name="saveData" id="saveData">Save Data</button>
1) Added jQuery to respond to that button being clicked (in the same *.ascx file):
$("#saveData").click(function () {
$('#hiddenSave').trigger('valuechanged');
});
2) Created a hidden element in the server-side C# (in the *.ascx.cs file):
HiddenField hiddenSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
hiddenSave = new HiddenField();
hiddenSave.ID = "hiddenSave";
hiddenSave.ValueChanged += new EventHandler(hiddenSave_ValueChanged);
this.Controls.Add(hiddenSave);
}
protected void hiddenSave_ValueChanged(object sender, EventArgs e)
{
GeneratePDF();
}
private void GeneratePDF()
{
;//bla
}
But I never reach the "ValueChanged" event handler; $("#saveData").click() fires, but not hiddenSave_ValueChanged().
So do I need a tweak to this, or a completely different approach? How can I do as much as possible client-side with jQuery, but also run server-side/C# code where necessary, in a Sharepoint 2010 app?
UPDATE
A little more detail, and about additional things I've tried: I'm creating a button on a Sharepoint page dynamically (in C#) in my *.ascx.cs file:
Button btnSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Visible = false;
this.Controls.Add(btnSave);
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Text = "You clicked me!";
PostTravelData ptd = new PostTravelData();
}
I set it visible at the right time in the client-side jQuery in the *.ascx file:
$('#btnSave').show();
However, clicking the button does not reach the btnSave_Click() event - the breakpoint there is never reached, nor is the button's text changed. Why not?
Even when I don't set the button invisible (comment out the "btnSave.Visible = false;" line), the click handler isn't reached...is Page_Load() too late? Is there an earlier page event I can use that would work?
I tried moving it from Page_Load() to OnPreRender(), too, like this:
protected void OnPreRender(EventArgs e)
{
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
//btnSave.Visible = false;
this.Controls.Add(btnSave);
}
...(and OnRender()) but the button doesn't even display...
And, trying a different tack, I commented out the dynamic creation server-side code and tried to attach to a button created in the HTML (*.ascx file):
<button type="button" name="saveData" id="saveData" runat="server" onclick="saveData_Click">Save Data</button>
(by adding the "runat server" and the onclick handler), and then adding this "code-behind" (*.ascx.cs)):
protected void saveData_Click(object sender, EventArgs e)
{
PostTravelData ptd = new PostTravelData();
SaveToList(ptd);
GeneratePDF(ptd);
}
...but there was still no joy in Mudville -- the breakpoint in the handler is not reached.
Yet another attempt was:
In the *.ascx:
<asp:Button runat="server" id="saveData" name="saveData" onclick="saveData_Click" Text="Bla" />
In the code-behind:
saveData.Click += saveData_Click;
The "Bla" button is created, but clicking on it reaches not the breakpoint in the "saveData_Click" handler.
I even adapted some code from here like so:
Button btnSave = null;
. . .
protected override void CreateChildControls()
{
btnSave = new Button();
btnSave.Width = new Unit(150, UnitType.Pixel);
btnSave.Text = "Can you see me?";
btnSave.Click += new EventHandler(btnSave_Click);
Controls.Add(btnSave);
}
...but I still do not reach the "protected void btnSave_Click(object sender, EventArgs e)" handler when I click the button.
Surely there's a way to get a handle on the button server-side and manipulate it (specifically, respond to its click event)...?!?
First of all, as far as I know, there is no such event for input type hidden in a ascx page. If you create the input type hidden with runat server in the ascx code then you'll see that when you try to add this event it's not available. However there are other events like OnClick that you can simulate to get the desired result.

C# web form listbox OnSelectedIndexChanged

I have a listbox on my website, which contains some elements.
I made the event, OnSelectedIndexChanged, so when the user presses an element, this value will be put into a textbox
protected void Page_Load(object sender, EventArgs e)
{
listbox = new Listbox();
// Add to page etc.
listbox.SelectedIndexChanged += new EventHandler(listbox_SelectedIndexChanged);
}
void listbox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
textbox_name.Text = listbox.SelectedItem.ToString();
}
catch
{
textbox_info.Text = "Choose employee";
}
}
It works in c# windows forms, but not in web forms for some reason.
Is it possible to get it to work?
Thank you
Set autopostback property of the listbox true

Event handler for groupBox with radioButtons in C#

I have some radionButtons in groupBox and I need to do action what I could call "one of radiobuttons.checked changed" or find out from radiobutton what index is changed.
I've tryed to find it in list of events but I couldn't find the right one.
Edit:
To make it more clear: I need to know if exist some handel for what I'll write handler method for the goupBox not for single radioButton. I know how to use radiButton.checkedChanged, but it's not what I'm finding ..
Or differently I need to know what options have the groupBox in monitoring what happens inside this groupBox - I mean only the handlers for the groupBox. I'm finding handler "in the group box is something happens" or simimilar if any exist.
It's in WFA (Windows Presentation Application) in Visual studio 2012.
I think what you want to do is wire up all of the RadioButtons' CheckedChanged event to the same handler.
public Form1()
{
radioButton1.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
// ...
}
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton1.Checked)
{
// Do stuff
}
else if (radioButton2.Checked)
{
// Do other stuff
}
}
Nothing built in for that as far as I'm aware.
Set the tag property to some sort of indicator (0 to n) will do.
Add a CheckChangedHandler
Point all the buttons CheckChanged events at it.
then something like.
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
int buttonid = (int)radioButton.Tag;
switch (buttonid)
{
case 0 : // do something; break
}
}
If you've got a few of these I'd look at a radiogroup component.
I had the same problem: a group box named Button Type (gbxButtonType) with 6 radio buttons and another group box named Icon Type (gbxIconType) with 8 radio button. When the user selected one radio button from each group box, a MessageBox will appear with the selection applied after clicking the DisplayButton. My problem was that the group boxes didn't have a CheckedChanged event. The solution of AKN worked perfectly:
public Form1()
{
InitializeComponent();
for (int i = 0; i < gbxButtonType.Controls.Count; i++)
{
RadioButton rdb = (RadioButton)gbxButtonType.Controls[i];
rdb.CheckedChanged += new System.EventHandler(gbxButtonType_CheckedChanged);
}
for (int i = 0; i < gbxIconType.Controls.Count; i++)
{
RadioButton rdb = (RadioButton)gbxIconType.Controls[i];
rdb.CheckedChanged += new System.EventHandler(gbxIconType_CheckedChanged);
}
}
private void gbxIconType_CheckedChanged(object sender, EventArgs e)
{
if (sender == rdbAsterisk)
{
iconType = MessageBoxIcon.Asterisk;
}
else if (sender == rdbError)
{
iconType = MessageBoxIcon.Error;
}
...
else
{
iconType = MessageBoxIcon.Warning;
}
}
Similar to davenewza's answer (and likely should have been a comment, but I have insufficient reputation), but with the event firing only once for the entire group of radio buttons.
public Form1()
{
// Add a "CheckedChanged" event handler for each radio button.
// Ensure that all radio buttons are in the same groupbox control.
radioButton1.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
}
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
// Do stuff only if the radio button is checked (or the action will run twice).
if (((RadioButton)sender).Checked)
{
if (((RadioButton)sender) == radioButton1)
{
// Do stuff
}
else if (((RadioButton)sender) == radioButton2)
{
// Do other stuff
}
}
}
Groupbox will limit only one radio button checked
So Setp1: you can assign one "CheckedChanged" event handler to all you radio button
private void initRadio()
{
radio_button1.CheckedChanged += Radio_show_CheckedChanged;
radio_button2.CheckedChanged +=Radio_show_CheckedChanged;
}
And Setp2: implement this event handler like this (Filter by Radio Button's Text)
private void Radio_show_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton.Checked == true) { //limited only checked button do function
switch (radioButton.Text)
{
case "name1":
// do your stuff ...
break;
case "name2":
// do your stuff ...
break;
}
}
}
System.Windows.Forms.RadioButton.CheckedChanged
is the event you need
So do something like:
public Form1()
{
InitializeComponent();
this.radioButton1.CheckedChanged += new EventHandler(radioButton1_CheckedChanged);
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
// your action
}
I think your want to handle the selection of some radio buttons inside a groupbox using the groupbox control itself.
May be you wanted this basically to avoid code repetition.
(i.e) adding check change event for all the radio button in the designer which may be tedious when there are more control.
Since its already present under a group, why not use the group control object to manipulate controls with-in it and set the events.
This is how I understood your problem and hence the solution as indicated below.
Set a common handler for all radio button control in the group box
for (int i = 0; i < groupBox.Controls.Count; i++)
{
RadioButton rb = (RadioButton)groupBox.Controls[i];
rb.CheckedChanged += new System.EventHandler(evntHandler);
}
Inside the handler, you can determine which button was changed as indicated by others and do the necessary action.
//Here you go courtesy of Jock Frank Halliday
//^subscribe events to radio button check changed
private void seriesTxtBxEvent()
{
//Show txtBx
this.radBtn_RoomSeries.CheckedChanged += new EventHandler(showSeriesTxtBx_Event);
//Hide txtBx
this.radBtn_RoomNumber.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
this.radBtn_RoomName.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
this.radBtn_RoomLevel.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
this.radBtn_RoomDep.CheckedChanged += new EventHandler(hideSeriesTxtBx_Event);
}
private void hideSeriesTxtBx_Event(object sender, EventArgs e)
{
tbx_SheetSeries.Visible = false;
}
private void showSeriesTxtBx_Event(object sender, EventArgs e)
{
tbx_SheetSeries.Visible = true;
}
//Form Start
void MainFormLoad(object sender, EventArgs e)
{
Control.ControlCollection locais = groupBoxLocalização.Controls;
foreach (CheckBox chkBox in locais)
{
chkBox.MouseUp += chkBoxLocais_MouseUp;
}
}
// Event
void chkBoxLocais_MouseUp(object sender, MouseEventArgs e)
{
//Tratar individualmente
CheckBox chk = (CheckBox)sender;
//ou para tratar todos objetos de uma vez
Control.ControlCollection locais = groupBoxLocalização.Controls;
foreach (CheckBox chkBox in locais) {
//chkBox....
}
}
You can maybe do it with Timer, but that's just bad for optimalization, the easy solution is that for every radiobutton you simply add only one function as ChekedChanged event.
Create a Checked event by double clicking on any of the radio buttons, copy the name of the method that Visual Studio creates for the event
Go to all radio buttons and change the event to the copied one from Properties Explorer > Events Section
In the generated method use the following code. This would fire event for all radio buttons but only "Do your thing" once
Code:
private void radioButtons_CheckedChanged (object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked == false) return;
// Do your thing
}
Create Event Checked_Changed on one radio button from Designer Events list.
Add same event to each radio Button from dropdown in front of Checked_Changed
event of each radio
inside checked changed event use
private void CheckedChanged(object sender,EventArgs e)
{
var radio = groupBox.Controls.OfType<RadioButton>
().FirstOrDefault(r => r.Checked).Name;
}
you can get which radio is active now.

Get the value of runtime added controls

HTML
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button runat="server" ID="show" OnClick="show_Click" Text="show"/>
<asp:Button runat="server" ID="add" OnClick="add_Click" Text="add new "/>
<div id="content" runat="server"></div>
</asp:Content>
code
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Checked);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}
by button add added a new checkbox on runtime.
then i want get checkbox chb by button show
but ((CheckBox) content.FindControl("chb")).Checked return Null.
i want add checkbox dynamically and then checked that which of them checked is true.
This happens because dynamically added controls are not preserved after postbacks. You can easily demonstrate this by adding another button (without a click event handler) to the page. Run the application and click the "add" button to create the checkbox, then click the newly added button and the checkbox will be gone after the postback.
Well, I can not understand what you are trying to achieve but;
protected void show_Click(object sender, EventArgs e)
{
Response.Write((Session["chb"] as CheckBox).Text);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
Session["chb"] = chb;
}
Your events don't happen in the same postback of your page - when you click add, it adds the checkbox but then the page execution finishes, the page is sent to the client and it's done with handling that Click event.
When you then click the show button, it's another postback, in which your checkbox has not been created, so it doesn't exist.
To handle this, you have a few options:
1.
Add the checkbox to the page in the designer and set its Visible property to false inially. You can keep the add button, but it won't actually add a checkbox to the page, it'll just make it visible by setting Visible to true.
2.
If you really want to dynamically add the checkbox, then you need to add it every time the page is executed, in one of the page event handlers (for example Load). The way to do that is to save a value in the viewstate or in a hidden field when you click add and based on the value, you'd create the checkbox on subsequent postbacks.
protected void Page_Load (object sender, EventArgs e)
{
if ( IsPostBack )
{
if ( Session["chb"] != null )
CreateChb ();
}
}
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Text);
}
protected void add_Click(object sender, EventArgs e)
{
Session["chk"] = true;
CreateChb ();
}
private void CreateChb ()
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}

how to handle programmatically added button events? c#

I'm making a windows forms application using C#. I add buttons and other controls programmatically at run time. I'd like to know how to handle those buttons' click events?
Try the following
Button b1 = CreateMyButton();
b1.Click += new EventHandler(this.MyButtonHandler);
...
void MyButtonHandler(object sender, EventArgs e) {
...
}
Use this code to handle several buttons' click events:
private int counter=0;
private void CreateButton_Click(object sender, EventArgs e)
{
//Create new button.
Button button = new Button();
//Set name for a button to recognize it later.
button.Name = "Butt"+counter;
// you can added other attribute here.
button.Text = "New";
button.Location = new Point(70,70);
button.Size = new Size(100, 100);
// Increase counter for adding new button later.
counter++;
// add click event to the button.
button.Click += new EventHandler(NewButton_Click);
}
// In event method.
private void NewButton_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
for (int i = 0; i < counter; i++)
{
if (btn.Name == ("Butt" + i))
{
// When find specific button do what do you want.
//Then exit from loop by break.
break;
}
}
}
If you want to see what button was clicked then you can do the following once you create and assign the buttons. Considering that you create the button IDs manually:
protected void btn_click(object sender, EventArgs e) {
Button btn = (Button)sender // if you're sure that the sender is button,
// otherwise check if it is null
if(btn.ID == "blablabla")
// then do whatever you want
}
You can also check them from giving a command argument to each button.
Check out this example How to create 5 buttons and assign individual click events dynamically in C#
seems like this works, while adding a tag with each element of the array
Button button = sender as Button;
do you know of a better way?
In regards to your comment saying you'd like to know which button was clicked, you could set the .Tag attribute of a button to whatever kind of identifying string you want as it's created and use
private void MyButtonHandler(object sender, EventArgs e)
{
string buttonClicked = (sender as Button).Tag;
}

Categories

Resources