samedi 30 novembre 2019

How to save checkbox item status in Checkedlistbox control in C# windows form application?

I have 2 Checkedlistbox controls in my C# windows form application program. First Checkedlistbox is for doctors' specialty for example dentist, radiologist and etc. If I check dentist checkbox doctors' specialty Checkedlistbox control, all doctors who are dentist will be shown in the doctors' name Checkedlistbox control.
The problem is that when I check dentist Checkedlistbox and then some dentists from doctors' Checkedlistbox, then if I check radiologist Checkedlistbox, then doctors' name Checkedlistbox will be reset and all my dentist checked checkbox will be de-selected.
What I have tried: Doctors' name Checkedlistbox data source:

DoctorsIDCheckedlistbox.DataSource = _ClinicEntities.Tbl_Doctors
      .Where(w => _SelectedSpecialty.Contains(w.SpecialtyID))
      .Select(s => new DoctorList { Name = s.Name + " " + s.LastName, DoctorID = s.DoctorID })
      .ToList();

DoctorsIDCheckedlistbox.DisplayMember = "Name";
DoctorsIDCheckedlistbox.ValueMember = "DoctorID";

Then I save checked items in ItemCheck event:

private void DoctorsID_ItemCheck(object sender, ItemCheckEventArgs e)
{
    int doctorID = Convert.ToInt32(DoctorsIDCheckedlistbox.SelectedValue);
    if (e.NewValue == CheckState.Checked)
    {
        _SelectedDoctorsChecked.Add(doctorID.ToString());
    }
    else
    {
        _SelectedDoctorsChecked.Remove(doctorID.ToString());
    }
}

Then for doctors' specialty ItemCheck event:

private void SpecialtyTypeID_ItemCheck(object sender, ItemCheckEventArgs e)
{
    for (int i = 0; i < DoctorsIDCheckedlistbox.Items.Count; i++)
    {
         if (_SelectedDoctorsChecked.Contains(DoctorsIDCheckedlistbox.Items[i].ToString()))
         {
             try
             {
                 DoctorsIDCheckedlistbox.SetItemChecked(i, true);
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.ToString());
             }
        }
    }
}

I expect code above look through _SelectedDoctorsChecked list which is selected doctors and check them when doctors' specialty checkboxes status changes. But it don't work.

Example:
I check A in doctors' specialty and items 1, 2 and 3 will be shown in doctors' name. I check 1 and 3. When I check B in doctors' specialty, Items 1, 2 and 3 from A and 4, 5 and 6 from B will be shown. I expect number 1 and 3 be checked. But it won't.




Aucun commentaire:

Enregistrer un commentaire