【问题标题】:Selecting checkboxlist checked items选择复选框列表选中的项目
【发布时间】:2012-12-23 09:08:53
【问题描述】:

我已尝试四处寻找解决问题的方法,但未能找到解决方案,因为似乎每个问题都比我的问题提前一两步。

我正在尝试从复选框列表中选择一个项目,而不是从中选择一个项目。

知道这一点后,我打算做的是使结果事件在单击按钮并选中选中的选项后触发,以在选中项目的标签中显示文本。

该程序基于装饰器模式,将允许用户从一组 3/4 可检查选项中进行选择,当按下按钮时,这些选项将在底座末端的标签中显示与这些项目相关的文本文本。目前,我所做的只是让它在选定的项目上一次执行一个,仅类似于第一个示例。

例如,当一个名为 Monitor 的选项被选中时,它会显示在标签中:

你得到一台电脑和一台显示器。

如果有多个检查项目,例如监视器和键盘,那么它会说:

你得到一台电脑、一个显示器和一个键盘。

【问题讨论】:

  • 只是想澄清一下,您想根据复选框勾选事件触发列表吗?
  • 是的,Windows 窗体应用程序。选项列表在应用程序启动时生成,用户按下所描述的事件的按钮,根据选中的选项显示在标签中的文本被触发。

标签: c# checkboxlist


【解决方案1】:

CheckedListBoxItemCheck 事件基于新的选中项值被触发时,您可以更改目标LabelLabel.Text 属性。

示例

假设您有一个名为label1Label、一个名为checkedListBox1CheckedListBox 和一个名为FormForm1,则可能适用以下情况

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        label1.Text = "You are getting "; //Change the Text property of label1 to "You are getting "
        checkedListBox1.ItemCheck += new ItemCheckEventHandler(checkedListBox1_ItemCheck); //Link the ItemCheck event of checkedListBox1 to checkedListBox1_ItemCheck; not required as long as you link the event through the designer
    }
    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.NewValue == CheckState.Checked && e.CurrentValue == CheckState.Unchecked) //Continue if the new CheckState value of the item is changing to Checked
        {
            label1.Text += "a " + checkedListBox1.Items[e.Index].ToString() + ", "; //Append ("a " + the item's value + ", ") to the label1 Text property
        }
        else if (e.NewValue == CheckState.Unchecked && e.CurrentValue == CheckState.Checked) //Continue if the new CheckState value of the item is changing to Unchecked
        {
            label1.Text = label1.Text.Replace("a " + checkedListBox1.Items[e.Index].ToString() + ", ", ""); //Replace ("a " + the item's value + ", ") with an empty string and assign this value to the label1 Text property
        }
    }
}

示例输入

[x] Monitor
[x] Keyboard
[ ] Mouse
[x] Computer

样本输出

You are getting a Monitor, a Keyboard, a Computer, 

谢谢,
希望对您有所帮助:)

【讨论】:

  • 该代码的第二行给了我 5 个错误: 1. 'Decorator_Pattern.Form1.checkedListBox1' 是一个“字段”,但用作“类型”。 2. 'Decorator_Pattern.Form1.checkedListBox1_ItemCheck(object, System.Windows.Forms.ItemCheckEventArgs)' 是一种“方法”,但用作“类型”。 3. 需要标识符(最后一个括号)。 4. 类、结构或接口成员声明中的标记“+=”无效。 5.方法必须有返回类型(对于'ItemCheckEventHandler')
  • @SergioJanuario 你应该在public Form1()InitializeComponent(); 之后执行此操作。祝你有美好的一天:)
  • 感谢您解决这个问题,现在可以使用了。感谢您的帮助。
  • @SergioJanuario 我很高兴能帮上忙。 Please notice that you may mark a post as an answer to indicate that you have already solved the problem。祝你有美好的一天:)
  • 我会先用它玩一会儿,以确保它是我在做任何其他事情之前正在寻找的东西。它工作正常,但我不确定它是否是我正在寻找的,因为它似乎在规避装饰器模式的工作方式,这也是我试图以此为基础并保持这种应用程序的方式。整晚都睡不着,不知道我还能熬夜玩它多久(如果我不尽快回复评论,这是我的原因)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 2013-01-23
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多