HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

A shorter way of Enablling/Disabling a text box from RadioButton selections

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromradiobuttontextwayselectionsenabllingdisablingshorterbox

Problem

Three radio buttons and a text box, grouped in one group box... Just when I select one of those radio button the text box gets enabled, for the other two radio buttons it should be disabled. Here is the code that comes to mind at first, but it looks ugly to me becuase I have copy pasted the same AllowMissingData() method to Change evnt of each radio button. I was wondering if there is a better way of writing it:

private void RequiredRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void AllowBlankRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void SuppressRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void AllowMissingData()
{
    if (AllowBlankRadioButton.Checked)
    {
        MissingDataValueTextBox.Enabled = true;
    }
    else
    {
        MissingDataValueTextBox.Text = System.String.Empty;
        MissingDataValueTextBox.Enabled = false;
    }
}

Solution

This cleans it up a little. Removes the if statement at least:

private void AllowMissingData()
{
    MissingDataValueTextBox.Enabled = AllowBlankRadioButton.Checked;
    MissingDataValueTextBox.Text = AllowBlankRadioButton.Checked ? MissingDataValueTextBox.Text : System.String.Empty;
}

Code Snippets

private void AllowMissingData()
{
    MissingDataValueTextBox.Enabled = AllowBlankRadioButton.Checked;
    MissingDataValueTextBox.Text = AllowBlankRadioButton.Checked ? MissingDataValueTextBox.Text : System.String.Empty;
}

Context

StackExchange Code Review Q#15483, answer score: 3

Revisions (0)

No revisions yet.