如何在C#中的checkedlistbox中默认选中两个项目

时间:2014-01-29 19:51:02

标签: c# winforms checklistbox

我有一个提示屏幕,弹出程序的乞讨,并要求用户选择他们想要更新的项目。 checklistbox中有5项。我想默认选择数据库和CGM选项。我现在拥有它的方式是检查checlistbox中的所有项目,然后将它们设置为未选中。我如何解决这个问题,以便默认选择CGM和数据库?

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

1 个答案:

答案 0 :(得分:1)

好像你只是在构造函数中执行它:

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