Determine if check status for radiobutton group has changed - c#

I have a group of 8 radiobuttons, is there a simple way to check if "checked" status has changed for the group? I don't need to know which button has been checked, just if a different button has been checked. Sort of like a CheckedChanged event for the whole group.

You can assign the same CheckedChanged event handler to all of the radiobuttons. When you check a radiobutton, the method will be called twice (for the radiobutton losing the checkmark and for the radiobutton being checked). So only handle the event for the one that is checked.
private void anyRadioButton_CheckedChanged(object sender, EventArgs e)
{
// The radio button that raised the event
var radioButton = sender as RadioButton;
// Only do something when the event was raised by the radiobutton
// being checked, so we don't do this twice.
if(radioButton.Checked)
{
// Do something here
}
}

I think what you are looking for is this, a common handler for all radio buttons in the group
radioButton1.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);

You can wire up all of the RadioButtons' CheckedChanged event to the same handler. Follow this code.
public Form1()
{
rB1.CheckedChanged += new EventHandler(rB_CheckedChanged);
rB2.CheckedChanged += new EventHandler(rB_CheckedChanged);
}
private void rB_CheckedChanged (object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (rB1.Checked)
{
}
else if (rB2.Checked)
{
}
}

Related

Fire event programmatically C#

I have several radio buttons inside a container. For each one I have the CheckedChangedevent so I have a code like this
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if ((sender as RadioButton).Checked)
// do stuff...
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if ((sender as RadioButton).Checked)
// do stuff...
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
if ((sender as RadioButton).Checked)
// do stuff...
}
// ... and so on...
Then I must fire the CheckedChanged event for the currently checked radioButton. To get the radioButton I used this code:
RadioButton checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
Now how can I fire the CheckedChanged event for checkedButton?
EDIT: I'm using WinForms. My radio buttons are in a tabPage. When I open the tabPage I need to know what is the currently checked radioButton and fire the corresponding checkedChanged event. This is because when I select another tabPage I perform other actions and, going back to the tabPage containing the radio buttons, I need to restore the previous state.
Changing the value of the Checked property should fire the event:
checkedButton .Checked = !checkedButton .Checked;
You may also call the event handler explicitly, e.g.:
RadioButton checkedButton = container.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked);
switch (checkedButton.Name)
{
case "radioButton1":
radioButton1_CheckedChanged(this, EventArgs.Empty);
break;
case "radioButton2":
radioButton2_CheckedChanged(this, EventArgs.Empty);
break;
case "radioButton3":
radioButton3_CheckedChanged(this, EventArgs.Empty);
break;
}
Depending on your requirements, you may of course want to consider using the same event handler for all RadioButtons.

Manage CheckedListBox ItemCheck event to run after an item checked not before

I am using CheckedListBox in C# Window Forms Application.
I want to do something after one item checked or unchecked but ItemCheck event runs before the item checked/unchecked .
How can I do that?
CheckedListBox.ItemCheck Event
The check state is not updated until after the ItemCheck event occurs.
To run some codes after the item checked, you should use a workaround.
Best Option
You can use this option (Thanks to Hans Passant for this post):
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
this.BeginInvoke(new Action(() =>
{
//Do the after check tasks here
}));
}
Another option
If in middle of ItemCheck Event, you need to know state of item, you should use e.NewValue instead of using checkedListBox1.GetItemChecked(i)
If you need to pass a list of checked indices to a method do this:
Using the code:
var checkedIndices = this.checkedListBox1.CheckedIndices.Cast<int>().ToList();
if (e.NewValue == CheckState.Checked)
checkedIndices.Add(e.Index);
else
if(checkedIndices.Contains(e.Index))
checkedIndices.Remove(e.Index);
//now you can do what you need to checkedIndices
//Here if after check but you should use the local variable checkedIndices
//to find checked indices
Another Option
In middle of ItemCheck event, remove handler of ItemCheck, SetItemCheckState and then add handler egain.
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
var control = (CheckedListBox)sender;
// Remove handler
control.ItemCheck -= checkedListBox_ItemCheck;
control.SetItemCheckState(e.Index, e.NewValue);
// Add handler again
control.ItemCheck += checkedListBox_ItemCheck;
//Here is After Check, do additional stuff here
}
Try searching more for answers, cause here it is
private void clbOrg_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox clb = (CheckedListBox)sender;
// Switch off event handler
clb.ItemCheck -= clbOrg_ItemCheck;
clb.SetItemCheckState(e.Index, e.NewValue);
// Switch on event handler
clb.ItemCheck += clbOrg_ItemCheck;
// Now you can go further
CallExternalRoutine();
}
And the link:
Which CheckedListBox event triggers after a item is checked?
You can hook up an event on ItemCheck. You can do it by right clicking your checkboxlist and select properties. And at the right side you will see the property tab, click the event tab button and locate ItemCheck event and double click it. It will generate a event method for you depend on your checkboxlist name like below.
Then, you can verify selected/checked checkbox using code below.
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
var checkBoxName = checkedListBox1.Items[e.Index];
Console.WriteLine("Current {0}, New {1} , value {2}", e.CurrentValue, e.NewValue, checkBoxName);
}

Radio button event executing two times

In my project, There are two radioButtons. To which I have given same CheckedChanged event by doing
something like this:
DoctorRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
PatientRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
I kept both the RadioButtons in a Panel to make them one true while other one is false.
Now the problem is that I am implementing a very big code in the RadioButton_CheckedChanged event.
Whenever the user is changing the state of any of the two RadioButtons, the event is raising two times.
After so many hours I got the answer, the event is raising two times because both the RadioButton states are being changed(Hence, the event will be raised two times). To solve this problem I am trying to unhook the event temporarily something like this:
RadioButton_CheckedChanged Event: (Not Working)
if (DoctorRadioButton.Checked)
{
PatientRadioButton.CheckedChanged -= RadioButton_CheckedChanged; //Un
//
//My functions
//
PatientRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
}
else
{
DoctorRadioButton.CheckedChanged -= RadioButton_CheckedChanged;
//
//My functions
//
DoctorRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
}
Eventhough the event is executing two times. I know I am doing something wrong in Hooking and Unhooking. Please Help.
You can check the sender RadioButton and place your code accordingly like this -
void RadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton senderRadioButton = sender as RadioButton;
if (senderRadioButton.Equals(DoctorRadioButton))
// OR senderRadioButton.Name == "DoctorRadioButton"
{
// Place your code here for DoctorRadioButton.
}
else
{
// Place your code here for PatientRadioButton.
}
}
Update
If you can't use two different handlers for both radioButtons and want to execute code only in case checkbox is checked you can do this -
void RadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton senderRadioButton = sender as RadioButton;
if (senderRadioButton.IsChecked)
{
// Place your code here for check event.
}
}
For an extremely simple (albeit crude) solution would be to not hook both the radio buttons, and hook only one of them to the handler: since checking one radio unchecks the other one, it would work as intended.
A more complicated way would be to use a backing property, like this:
class myForm
{
private bool radioStatus = false; // depends on the default status of the radios
private bool RadioStatus
{
get{return radioStatus;} set {radioStatus = value; Checked_Changed();}
}
public myForm()
{
// Lambdas as handlers to keep code short.
DoctorRadioButton.CheckedChanged += (s,args)=>
{ if((s as RadioButton).Checked) RadioStatus = true; };
PatientRadioButton.CheckedChanged += (s,args)=>
{ if((s as RadioButton).Checked) RadioStatus = false; };
}
void Checked_Changed()
{
if (RadioStatus) // = true --> DoctorRadioButton was checked
{
//code
}
else // = false --> PatientRadioButton was checked
{
//other code
}
}
}
This approach has the advantage of allowing you to abstract from the UI a bit.
Put both radio buttons in the same panel or groupbox and automatically they will be grouped so that only one can be selected at a time.
Its a late solution but i found there is no correct answer for your question so i am posting it may be it works For You
Create Click Event for both radio button and simple put your code beacuse on every click your radio button got checked and your code executes :):):)
private void DoctorRadioButtons_Click(object sender, EventArgs e)
{
//Your code on Doctor Radio Button
}
private void PatientRadioButton_Click(object sender, EventArgs e)
{
// Your code on Patient Radio Button
}

Add Dynamic CheckBox Handle CheckedChanged Event ASP.NET

I would like to know why the event is not firing & how to find which checkbox control fired the event.
chkList1 = new CheckBox();
chkList1.Text = row["subj_nme"].ToString();
chkList1.ID = row["subjid"].ToString();
chkList1.Checked = true;
chkList1.Font.Name = "Verdana";
chkList1.Font.Size = 12;
chkList1.AutoPostBack = true;
chkList1.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
Panel1.Controls.Add(chkList1);
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
Label1.Text = "Called";
}
If the events aren't firing, it's likely for one of two reasons:
The controls are recreated too late in the page lifecycle. Try creating the controls during OnInit.
Validation is preventing the postback. To work around this you can set CausesValidation to false on all of the CheckBox controls.
You can find out which control triggered the event using the sender argument.
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
//write the client id of the control that triggered the event
Response.Write(((CheckBox)sender).ClientID);
}

dataGridView ComboBox Event Handler Problem

I am having a problem with the handling of an index changed event for a comboBox that resides inside a dataGridView. I write an method to handle the comboBox selection change using either a delegate:
ComboBox.SelectedIndexChanged -= delegate { ComboBoxIndexChanged(); };
ComboBox.SelectedIndexChanged += delegate { ComboBoxIndexChanged(); };
or an EventHandler:
comboBox.SelectedIndexChanged += new EventHandler(ComboBoxIndexChanged);
but both methods do not work as expected. That is, when you click on your selection within the comboBox (contained within the dataGridView) it takes multiple clicks to cause my ComboBoxIndexChanged(); method to function proper, that if it decides to function at all. What is the best way to overcome/go-about specifying an event on an indexedChange of a comboBox within a dataGridView?
The code I am currently using in context is as follows:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
if (this.dataGridView.CurrentCell.ColumnIndex == (int)Column.Col)
{
ComboBox comboBox = e.Control as ComboBox;
if (comboBox != null)
{
comboBox.SelectedIndexChanged += new EventHandler(ComboBoxIndexChanged);
}
}
return;
}
catch (Exception Ex)
{
Utils.ErrMsg(Ex.Message);
return;
}
}
and the event ComboBoxIndexChanged is:
private void ComboBoxIndexChanged(object sender, EventArgs e)
{
// Do some amazing stuff...
}
I have read a similar thread on StackOverFlow which states that there is a problem with dealing with the comboBox change event this way, but I cannot get the solution to work. The post can be found here: "SelectedIndexChanged" event in ComboBoxColumn on Datagridview. It says:
"Things get complicated since they optimized the DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation:
First hook up a delegate to the EditControlShowing event:
myGrid.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(
Grid_EditingControlShowing);
...
Then in the handler, hook up to the EditControl's SelectedValueChanged event:
void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// the event to handle combo changes
EventHandler comboDelegate = new EventHandler(
(cbSender, args) =>
{
DoSomeStuff();
});
// register the event with the editing control
combo.SelectedValueChanged += comboDelegate;
// since we don't want to add this event multiple times, when the
// editing control is hidden, we must remove the handler we added.
EventHandler visibilityDelegate = null;
visibilityDelegate = new EventHandler(
(visSender, args) =>
{
// remove the handlers when the editing control is
// no longer visible.
if ((visSender as Control).Visible == false)
{
combo.SelectedValueChanged -= comboDelegate;
visSender.VisibleChanged -= visibilityDelegate;
}
});
(sender as DataGridView).EditingControl.VisibleChanged +=
visibilityDelegate;
}
}"
This issue I have with this is that "VisSender" is not defined hence the event "VisibleChanged" cannot be used.
Any help from you lads, is as always, most appreciated.
Sounds like you want the changes to be committed as soon as the user changes the drop down box, without them having to click off of the cell. In order to do this you will need to force the commit when the change happens (using CommitEdit, there is also an example on the MSDN page). Add this to your DataGridView:
// This event handler manually raises the CellValueChanged event
// by calling the CommitEdit method.
void dataGridView1_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Then you could just listen for the CellValueChanged and avoid having to try and register for the ComboBoxValueChanged event on the underlying editing control.

Categories