I have a menu with checkboxes (for example, Settings > Use HTTP/HTTPS/SOCKS5 - 3 different checkboxes) and I want to make it so that when one checkbox is selected others get unselected automatically.
My idea was to use some kind of loop to go through each element and unselect them except the selected one.
I tried like this:
foreach (ToolStripItem mi in settingsToolStripMenuItem)
{
// code to unselect here
}
But I can't figure it out.
In click event handler for sub menu, you can uncheck all items and check only clicked item:
private void SubMenu_Click(object sender, EventArgs e)
{
var currentItem = sender as ToolStripMenuItem;
if (currentItem != null)
{
//Here we look at owner of currentItem
//And get all children of it, if the child is ToolStripMenuItem
//So we don't get for example a separator
//Then uncheck all
((ToolStripMenuItem)currentItem.OwnerItem).DropDownItems
.OfType<ToolStripMenuItem>().ToList()
.ForEach(item =>
{
item.Checked = false;
});
//Check the current items
currentItem.Checked = true;
}
}
Notes:
((ToolStripMenuItem)currentItem.OwnerItem)
to find the owner of clicked item to be more general to be reusable for every case you need such functionality. If there using System.Linq;
is not present in usings of your class, add it.
If your checkbox is inside a ToolStripControlHost, You can do this on the checkbox's CheckedChanged
event:
foreach (ToolStripItem mi in settingsToolStrip.Items) {
ToolStripControlHost item = mi as ToolStripControlHost;
if (item != null) {
if (item.Control is CheckBox) {
// put your code here that checks all but the one that was clicked.
((CheckBox)item.Control).Checked = false;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.