lundi 3 août 2020

Change state of checkbox by Listbox items selection c#

I have a listboxnamed (lstClass) filled with database items. I want to change the state of checkbox named (cbSelectAll) placed outside the listbox. I want these points to implement in code,

  1. When form loads, the Checkbox should be set to false.
  2. When I select multiple items(Not complete items) from Listbox, Checkbox state should be changed to Intermediate.
  3. When I select complete items form Listbox, Checkbox state should be changed to True.
  4. When I Click checkbox, if its state is true then all items should be selected in ListBox.
  5. When I click checkbox, if its state is false then no items should be selected in Listbox.

The code for the form is under:-

public partial class frmSelectClass : Form
{
    private DataTable dTable;
    
    public frmSelectClass(DataTable table)
    {
        InitializeComponent();
        this.dTable = table;
    }

    private void frmSelectClass_Load(object sender, EventArgs e)
    {
        Retrieving_SheetNames();
    }

    private void Retrieving_SheetNames()
    {
        List<string> lstSheets;
        // Get sheet names from excel
        List<string> lstSheetsEx = dTable.AsEnumerable()
                   .Select(r => r.Field<string>("TABLE_NAME").Trim(new char[] { '\'', '$' })).ToList();
        using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
        {
            using (OleDbCommand command = new OleDbCommand("select * from Classes", conn))
            {
                conn.Open();
                DataTable dtClassDb = new DataTable();
                dtClassDb.Load(command.ExecuteReader());
                // Get sheet names from Access DB
                List<string> lstSheetsdb = dtClassDb.AsEnumerable().Select(c => c.Field<string>("Class")).ToList();
                // Order sheet names according to DB
                lstSheets = lstSheetsdb.Intersect(lstSheetsEx).Union(lstSheetsEx).ToList();
            }
        }
        lstClass.DataSource = lstSheets;
    }
   
    private void cbSelectAll_CheckedChanged(object sender, EventArgs e)
    {
        if (cbSelectAll.Checked)
        {
            for (int i = 0; i < lstClass.Items.Count; i++)
            {
                lstClass.SetSelected(i, true);
            }
            return;
        }
        for (int i = 0; i < lstClass.Items.Count; i++)
        {
            lstClass.SetSelected(i, false);
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire