Thomas O'Connor
Thomas O'Connor

Reputation: 33

How can several user controls respond to an event that occurs in one of them in c#?

I have a user control that consists of a checkbox. I have 4 of these user controls on a form. When the user clicks any one of the checkboxes in the user control, I want the other user controls to ensure they are not checked. Similar to the way that radio buttons would work, except I need to use checkboxes and events.

Upvotes: 0

Views: 171

Answers (4)

aked
aked

Reputation: 5835

OK , if i am assuming right . you got 4 usercontrols in a form and they need to communicate with each other on some event ( in your case it is event caused by checkbox in one of your user control)

I would implement subscriber /publisher model.
In Usercontrol-A (publisher) 1) On checkbox click raise a event , forward this to a common event function

Page class which contains the usercontrol , will subscribe to the event of UsercontrolA and if required forward it to Usercontrol B (subscriber)

for more details see this http://www.codeproject.com/Articles/15550/How-to-invoke-events-across-User-Controls-in-ASP-N

Upvotes: 0

Omar
Omar

Reputation: 16623

A simple way could be use a single method for all the events of the CheckBoxes and exploit the sender object in this way:

List<CheckBox> listCheckBoxes;

checkBox1.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
checkBox2.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
checkBox3.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
checkBox4.CheckedChanged += new EventHandler(checkBox_CheckedChanged);

listCheckBoxes = this.Controls.OfType<CheckBox>().ToList();

void checkBox_CheckedChanged(object sender, EventArgs e){
    CheckBox checkBox = (CheckBox)sender;
    if(checkBox.Checked){
        foreach(CheckBox c in listCheckBoxes){
            if(c.Checked && c != checkBox)
               c.Checked = false;
        }
    }
}

Upvotes: 3

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

Wrap up the controls in a single UserControl. When an event fires on a single CheckBox control raise a general toggle event for the remaining CheckBox controls.

Upvotes: 1

D Stanley
D Stanley

Reputation: 152634

The event handler is typically a method of the form (or a custom container). You typically know about other controls at that level. If you're trying to execute that event handler on the custom control itself you're going to have issues because you'll be tying the control to other controls.

It would be a better design to have some sort of container control that has an event handler to perform this logic. That event handler would then be added to the Click event of each of the checkboxes.

Upvotes: 1

Related Questions