Question

I have 3 radio buttons all held within a groupbox (so only 1 can be marked at a time). I've got my code working, but to be quicker on updating my label, I want to stop the function from being called twice when a new radioButton is selected.

For instance, in my code below, my default is rb1 and then I click rb2, the rb1 CheckedChanged Event fires and updates the label, then rb2's CheckedChanged Event fires and updates the label again (same value).

What would be the best way to add some extra criteria to where if the label has been updated once, then stop the function from being called again?

CODE:

private void rb1_CheckedChanged(object sender, EventArgs e)
    {
        if (cmbLetterType.Text.Length != 0)
        {
            updatePrintedCntLabel();
        }
    }

private void rb2_CheckedChanged(object sender, EventArgs e)
{
    if (cmbLetterType.Text.Length != 0)
    {
        updatePrintedCntLabel();
    }
}

private void rb3_CheckedChanged(object sender, EventArgs e)
{
    if (cmbLetterType.Text.Length != 0)
    {
        updatePrintedCntLabel();
    }
}

EDIT: To clarify, this is a C# Winforms application I'm doing this in.

Was it helpful?

Solution 2

Change your condition to:

if (cmbLetterType.Text.Length != 0 && rb1.Checked)

Do this for the other 2 handlers as well (using rb2.Checked and rb3.Checked) and each one will only fire when it's the one that's become checked, not unchecked.

OTHER TIPS

Consider this

public class Form1 : Form 
{


    public Form1()
    {
        rb1.CheckedChanged += rb_CheckedChanged;
        rb2.CheckedChanged += rb_CheckedChanged;
        rb3.CheckedChanged += rb_CheckedChanged;
    } 

    private void rb_CheckedChanged(object sender, EventArgs e)
    {

        if (!((Radiobutton)sender).Checked) return;

        if (cmbLetterType.Text.Length != 0)
        {
            updatePrintedCntLabel();
        }

    }
}

The events are doing what are telling them to do

If you don't want to update the Label twice then don't
Simple, if the value did not change then don't update
Save the value and test for change

Why do you have three identical event handlers?
You can wire multiple events to the same handler.

Even if you use the approach from Baldrick you can get the button from sender.

Late tag on WinForm but still can use the same approach ( if (labelVal = value) return; )
In general use public properties

private string labelVal = string.empty;

public string LabelVal
{
    get { return labelVal; } 
    set
    { 
        if (labelVal = value) return;
        labelVal = value;
        NotifyPropertyChanged("LableVal");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top