【问题标题】:C# Foreach checkbox checked in a panel在面板中选中的 C# Foreach 复选框
【发布时间】:2013-12-30 20:13:32
【问题描述】:

我正在尝试检查面板 1 中选中的每个复选框。然后显示在 label1 中检查的项目。我无法让它与面板和复选框一起使用......下面是我的代码。任何建议都会很棒! 谢谢

foreach (int indexChecked in panel1)
{
            str1 += panel1.Items[indexChecked].ToString() + ", ";
            label1.Visible = true;
}
        label14.Text = str1;

【问题讨论】:

  • 似乎是什么问题,你得到什么错误?你所说的“不能让它工作”是什么意思它编译了吗,你得到什么输出?
  • 另外,为您的控件命名!面板 1、标签 1、标签 2、标签 3。一旦应用程序变大就很难阅读,不断检查哪个是哪个。

标签: c# checkbox foreach indexing panel


【解决方案1】:

解决方案 1:

   String str1="";
   foreach (Control c in panel1.Controls)
    {
        if((c is CheckBox) && ((CheckBox) c).Checked)                      
        str1 += c.Text+ ", "; 
    }

    str1=str1.Trim();
    str1=str1.Substring(0,str1.Length-1);
    label14.Text = str1;

解决方案2:如果要将每个选中的CheckBox 项添加到ListView

试试这个:

   listView1.Items.Clear();
   foreach (Control c in panel1.Controls)
    {
        if((c is CheckBox) && ((CheckBox) c).Checked)                      
          listView1.Items.Add(c.Text);
    }

【讨论】:

  • 这太完美了!!最后一个问题,我如何在列表视图中显示它。如果选中了多个复选框,是否让它们开始新行?
  • @hexc: 那么你想在列表视图的新行中显示每个复选框文本吗?
  • 只在标签或列表视图中显示每个复选框,但对于每个选中的复选框,它都会换行。
  • @hexc:用solution 2检查我编辑的答案,如果对你有帮助,请将其标记为答案。
  • @hexc: 不客气 :) 很高兴能帮到你。
【解决方案2】:

checkbox是否被勾选可以直接获取:

foreach (Control c in Controls.OfType<CheckBox>())
            {
                if (((CheckBox)c).Checked == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

【讨论】:

  • Controls.OfType 在 ASP.net 中不存在
  • 它在 Asp.Net 中可用,我的示例代码基于 ASP.Net
猜你喜欢
  • 2014-10-25
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2013-01-10
  • 2023-03-18
  • 2018-04-18
  • 1970-01-01
相关资源
最近更新 更多