如何在C#Windows窗体应用程序的Checkedlistbox控件中保存复选框的状态?

问题描述 投票:1回答:1

我在C#Windows窗体应用程序中有2个Checkedlistbox控件。首先Checkedlistbox用于医生的专科,例如牙医,放射线医生等。如果选中“牙医”复选框,则医生的专科Checkedlistbox控件将显示在医生的名称Checkedlistbox控件中。问题是,当我检查牙医Checkedlistbox,然后再检查医生Checkedlistbox的一些牙医时,如果我检查放射科医生Checkedlistbox,则医生的姓名Checkedlistbox将被重设,并且我所有牙医检查的复选框都将被取消选择。我尝试过的医生的名字Checkedlistbox数据源:

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

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

然后我将选中的项目保存在ItemCheck事件中:

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());
    }
}

然后参加医生专业ItemCheck活动:

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());
             }
        }
    }
}

[我希望上面的代码通过_SelectedDoctorsChecked列表查找被选择的医生,并在医生的专业复选框状态更改时对其进行检查。但这不起作用。

示例:我在医生的专长中选中A,并且项目1、2和3将显示在医生的名字中。我检查1和3。当我在医生专业中检查B时,将显示A中的项目1、2和3和B中的4、5和6。我希望检查1号和3号。但是不会。

编辑:我的Checkedlistbox控制数据源:

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

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

DoctorListCheckbox类:

 public partial class DoctorListCheckbox
 {
    public int DoctorID { get; set; }
    public string Name { get; set; }
    public CheckState CheckState { get; set; }
    public override string ToString()
    {
        return Name;
    }
 }

我基于Microsoft Example做到了

c# .net winforms data-binding checkedlistbox
1个回答
1
投票

基本知识与我在Updates in the DataSource reset CheckedListBox checkboxes中所解释的相同。

© www.soinside.com 2019 - 2024. All rights reserved.