How to activate / deactivate checklist items dynamically according to checked items?
I have checkboxlist
one that contains a list of services loaded from a database table. Each of these services can only run one or with some other specific services. For example, if I select "Transfer Property", I cannot select "Register" at the same time.
I have a table that contains the relationship between services and which services can be selected along with each service (did I explain this correctly?).
I need to click a service and then disable / deny checking all services that are not associated with that service and re-enable those items when I uncheck the parent item ...
Is there a good way to do this? I mean, is there a way to do this?
a source to share
First of all, your CheckBoxList must have AutoPostBack set to true.
I believe the key to what you are looking for is
CheckBoxList1.Items.FindByText(service).Enabled = false;
or does this work too
CheckBoxList1.Items.FindByText(service).Attributes.Add("disabled", "disabled");
in context, it might look something like this:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
//first reset all to enabled
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
CheckBoxList1.Items[i].Attributes.Remove("disabled", "disabled");
}
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
//get list of items to disable
string selectedService = CheckBoxList1.Items[i].Text;
List<string> servicesToDisable = getIncompatibleFor(selectedService);//this function is up to u
foreach (string service in servicesToDisable)
{
CheckBoxList1.Items.FindByText(service).Attributes.Add("disabled", "disabled");
}
}
}
}
a source to share
void ControlCheckBoxList(int selected, bool val)
{
switch (selected)
{
case 1:
case 2:
case 3:
checkedListBox1.SetItemChecked(5, !val);
break;
case 6:
checkedListBox1.SetItemChecked(1, true);
break;
default:
checkedListBox1.ClearSelected();
break;
}
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
ControlCheckBoxList(e.Index, e.NewValue == CheckState.Checked ? true : false);
}
a source to share
Well, javascript is perhaps best suited for this client side, otherwise you might try something like this in your code.
List<Service> services = new List<Service>(); //get your services
foreach (ListItem li in lstRoles.Items)
{
Predicate<Service> serviceIsAllowed = delegate (Service s) { return /*some expression using s and li.Value (or use a lambda expr) */; }
li.Selected = services.Find(serviceIsAllowed) != null;
}
a source to share