Domanda

I have created a class that I want to return the selected value from a combo box, checkbox or text box.

The code looks like this:

private string GetControlValue(string controlId)
    {
        var control = FindControl(controlId);

        if (control.GetType() == typeof(RadTextBox))
        {
            return ((RadInputControl)control).Text;
        }
        else if (control.GetType() == typeof(RadComboBox))
        {
            return ((RadComboBox)control).SelectedValue;
        }
        else if (control.GetType() == typeof(CheckBox))
        {
            return ((CheckBox)control).Checked.ToString();
        }
        else
        {
            return null;
        }
    }

Can I do this in some more efficient way? I guess my example may be boxing each type and it pulls down performance.

È stato utile?

Soluzione

You could use the inheritance tree to shorten the code:

private string GetControlValue(string controlId)
{
    var control = FindControl(controlId);
    if(control is ITextControl)
    {
        return ((ITextControl) control).Text; // works also for the RadComboBox since it returns the currently selected item's text
    }
    else if(control is ICheckBoxControl)
    {
        return ((ICheckBoxControl)control).Checked.ToString();
    }
    else
    {
        return null;
    }
}

Altri suggerimenti

You can use the as keyword:

private string GetControlValue(string controlId)
{
    var control = FindControl(controlId);
    var radTextBox = control as RadTextBox;
    if (radTextBox != null)
    {
        return radTextBox.Text;
    }

    var radComboBox = control as RadComboBox;
    if (radComboBox != null)
    {
        return radComboBox.SelectedValue;
    }

    var checkBox = control as CheckBox;
    if (checkBox != null)
    {
        return checkBox.Checked.ToString();
    }

    return null;
}

BTW: Boxing is not happening in your code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top