【问题标题】:Recognize CheckedListBox item has been selected识别 CheckedListBox 项目已被选中
【发布时间】:2012-10-25 14:24:33
【问题描述】:

直到现在我才处理过checkedListBox1。我想制作的程序将受益于使用它,而不必使用大量的复选框。

我有代码:

private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    int selected = checkedListBox1.SelectedIndex;
    this.Text = checkedListBox1.Items[selected].ToString();
}

这样做的问题是,每次我单击框并突出显示时,它都会选择突出显示的对象。我正在寻找的是识别所选内容的变化,而不是突出显示。

我还想知道的是,如果 CheckListBox 中的第一个索引项和第三个一样被选中,我将如何检查它是否为真?

我确信我最终会弄明白的,但是看到代码会有很大帮助。

假设我有 3 个盒子: 框 A = messageBox.Show("a"); 框 B = messageBox.Show("b"); 框 C = messageBox.Show("c");

只有选中该框时才会显示 mbox。我想知道的是如何让它检查是否检查了例如 A 和 C 以便如果我按下一个按钮,两个消息框将显示“a”然后显示“c”

【问题讨论】:

  • 你试过OnItemCheck吗?
  • Winforms,对不起,我应该补充一下。
  • rudi_visser,介意给我举个例子吗?

标签: c# winforms checkedlistbox selectedindexchanged


【解决方案1】:
   private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        // a checkbox is changing
        // but value is not updated yet

    }

    private void checkedListBox1_MouseUp(object sender, MouseEventArgs e)
    {
        Debug.WriteLine(checkedListBox1.CheckedItems.Count);
        Debug.WriteLine(checkedListBox1.CheckedItems.Contains(checkedListBox1.Items[0]));
    }

我认为你应该在 MouseUp 中检查第一个是否被选中。 _ItemCheck 用于复选框正在更改但值尚未更新时。

见参考:http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.items.aspx

   // First show the index and check state of all selected items. 
foreach(int indexChecked in checkedListBox1.CheckedIndices) {
    // The indexChecked variable contains the index of the item.
    MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" +
                    checkedListBox1.GetItemCheckState(indexChecked).ToString() + ".");
}

// Next show the object title and check state for each item selected. 
foreach(object itemChecked in checkedListBox1.CheckedItems) {

    // Use the IndexOf method to get the index of an item.
    MessageBox.Show("Item with title: \"" + itemChecked.ToString() + 
                    "\", is checked. Checked state is: " + 
                    checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
}

【讨论】:

  • 每当我点击第一个(值 = 0)、第三个(值 = 2)以及之后的任何一个时,我都会得到 bool="False" 但在第二个检查项目上我会得到一个“真”回报。让我编辑我的主要帖子以澄清问题。
  • 这有帮助。我可以使用那里提供的东西,想知道我怎么没有看到微软的那个页面。
【解决方案2】:

如果您想获取所有选中项的集合,请使用checkedListBox1.CheckedItems。要在单击按钮时显示所有选中的项目,请使用以下命令:

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
        MessageBox.Show(checkedListBox1.CheckedItems[i].ToString());
}

如果您只需要它们的索引,请改用checkedListBox1.CheckedIndices。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2014-12-04
    • 1970-01-01
    相关资源
    最近更新 更多