开发者

Get Checked Value for Both RadioButtons and CheckBoxes in C#

So I have an event that can be triggered by a change of the checked value of some checkboxes and some radiobuttons. I want to get the Checked value of the control that triggered the event. I know that if it is a checkbox I can do something like bool checkedValue = (sender as CheckBox).Checked; (a开发者_高级运维nd same for radiobuttons). but what if I don't know the type of the control? Is there a class for both of them?


The best approach would be to use an interface, but according to your comment on Felice Pollano's answer you don't want to.

I would then suggest to look for the type at runtime:

bool checked;
if (sender is CheckBox)
 checked = ((CheckBox)sender).Checked;
if (sender is RadioButton)
 checked = ((RadioButton)sender).Checked;


If you are running .NET 4 you might want to try this ugly trick:

private void checkBox1_Click(dynamic sender, EventArgs e) {
    bool isChecked = sender.Checked;
    textBox1.Text = isChecked ? "Checked" : "Unchecked";
}

not very type safe, but fun!


You may build a small function taking a control parameter. Then try to cast first to Check box, if not null use the Checked result. If null, try the same with radio button. If that's null too, throw an InvalidParameterException or something appropriate. Else return the value you saved.

bool GetChecked(object ctrl) {
    bool result = false;
    CheckBox cb = ctrl as CheckBox;
    if ( null == cb ) {
        RadioButton rb = ctrl as RadioButton;
        if ( null == rb ) {
             throw new Exception ( "ctrl is of the wrong type " );
        }
        result = rb.Checked;
    } else {
        result = cb.Checked;
    }
    return result;
}

Not tried to compile, just to provide the idea. Second idea: do a bit reflection, look if there's a property named Checked and get the value. Rough, untested Code:

bool GetChecked(object ctrl) {
    bool result = false;
    Type reflectedResult = ctrl.GetType();
    PropertyInfo[] properties = reflectedResult.GetProperties();
    List<System.Reflection.PropertyInfo> properties = ctrl.GetProperties ().Where ( itm => itm.Name == "Checked" ).ToList ();
    if ( properties.Count == 1 )
    {
        bool result = (bool)properties[0].GetValue ( ctrl, null );
    } else {
        throw new Exception ( "ctrl is of the wrong type " );            
    }     
    return result;
}

Though I don't like the code of both...


They both derive from ButtonBase but ButtonBase does not implement IsChecked. As a suggestion create two subclass of CheckBox and RadioButton, declare an Interface, ie IHasCheck, implement it properly in your derived classes, and try to cast at this interface in the event handler:

 public interface ICheckable
    {
        bool Checked { get; set; }
    }
    class RadioButtonExtended : RadioButton,ICheckable
    {

    }
    class CheckBoxExtended : CheckBox, ICheckable
    { 
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜