V_H24
V_H24

Reputation: 139

How to checkmark by default two items in checklistbox in C#

I have a prompt screen which pops in the begging of the program and asks the users to select the items that they wanted to be updated. there are 5 items in checklistbox. I wanted to select by default the Database and CGM options. The way that I have it right now it checks for all the items in the checlistbox and then sets them to unchecked. How I can fix this so the CGM and Database should be selected by default?

public partial class PromptScreen : Form
{        
    public PromptScreen()
    {
        InitializeComponent();
        this.Icon = Properties.Resources.TDXm;
        for (int i = 0; i < cLbFiles.Items.Count; i++)
            dictionary.Add(cLbFiles.Items[i].ToString(), CheckState.Unchecked);
    }
    private void clbFiles_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        foreach (KeyValuePair<string, CheckState> kvp in dictionary)
        {
            if (kvp.Key == cLbFiles.Items[e.Index].ToString())
            {
                dictionary[kvp.Key] = e.NewValue;
                if (kvp.Key == "Component Views")
                {
                    if (kvp.Value == CheckState.Unchecked)
                        MessageBox.Show("Updating Component Views! This might take up to 5 minutes", "Wait Warning", 
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                break;
            }
        }
    }

    private void btnCGMDB_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < cLbFiles.Items.Count; i++)
        {
            if (cLbFiles.Items[i].ToString() == "CGM's" || cLbFiles.Items[i].ToString() == "Database")
                cLbFiles.SetItemChecked(i, true);
        }
        btnUpdate.PerformClick();
    }
}

Upvotes: 2

Views: 200

Answers (1)

itsme86
itsme86

Reputation: 19496

It seems like you'd just do it in the constructor:

public PromptScreen()
{
    InitializeComponent();
    this.Icon = Properties.Resources.TDXm;

    string[] checkByDefault = new[] { "CGM's", "Database" };
    for (int i = 0; i < cLbFiles.Items.Count; i++)
    {
        string itemString = cLbFiles.Items[i].ToString();
        dictionary.Add(itemString, checkByDefault.Contains(itemString) ? CheckState.Checked :  CheckState.Unchecked);
}

Upvotes: 1

Related Questions