【问题标题】:How to count the total no. of asp.net checkboxes, checkboxes checked, no. of checkboxes remain unchecked in webform using vb.net?如何计算总数。 asp.net 的复选框,选中的复选框,没有。使用 vb.net 在网络表单中未选中的复选框?
【发布时间】:2010-12-09 04:12:16
【问题描述】:

如何计算总数。 asp.net 的复选框,选中的复选框,没有。的复选框在使用 vb.net 的网络表单中保持未选中状态?

我正在使用 Visual Studio 2008 和 vb 作为语言..

我的网络表单有 10 个复选框...

我想计算总数。文本框1中网络表单中的复选框 总数在 textbox2 的 web 表单中选中的复选框 总数的复选框在 textbox3 中的 web 表单中保持未选中

【问题讨论】:

    标签: asp.net vb.net


    【解决方案1】:

    这是一个示例 C# 代码,您可以从中轻松开发 VB 代码。

    private int mTotal;
    private int mChecked;
    
    private void EnumerateCheckBoxes(Control control)
    {
       if (control is CheckBox)
       {
         mTotal++;
         mChecked += ((CheckBox)control).Checked ? 1 : 0;
       }
       else if (control.HasControls())
       {
         foreach(var c in control.Controls) 
         {
           EnumerateCheckBoxes(c);
         }
       }
    }
    
    protected void Page_Load(Object sender, EventArgs e)
    {
       mTotal = 0;
       mChecked = 0;
       EnumerateCheckBoxes(this.Form);
       textbox1.Text = mTotal.ToString();
       textbox2.Text = mChecked.ToString();
       textbox3.Text = (mTotal - mChecked).ToString();
    }
    

    需要考虑的几件事:

    1. 此代码将计算单选按钮,因为它继承自 CheckBox。如果要避免这种情况,请将if (control is CheckBox) 替换为if (control.GetType() == typeof(CheckBox))
    2. 如果您希望考虑 CheckBoxList 中的复选框,那么您必须编写另一个条件来查看控件是否为 CheckBoxList,然后在条件内使用复选框列表枚举项目。项目计数要添加到总计数中,而选定的项目要添加到检查计数中。

    【讨论】:

    • 打败我。我尝试了一个实际的 VB 答案并被语言所困扰。尝试使用 LINQ 选择所有 CheckBox 控件时,我也分心了。 :-)
    【解决方案2】:
    Dim intTotalCheckBoxes as Integer = 0
    Dim intCheckBoxesChecked as Integer = 0
    Dim intCheckBoxesUnChecked as Integer = 0
    
    For Each chkbox as Checkbox in Page.Controls
    
    If chkbox.Checked Then
    
       intCheckBoxesChecked += 1
    
    Else
    
       intCheckBoxesUnChecked += 1
    
    End If
    
    intTotalCheckBoxes += 1
    
    Next
    

    如果您的页面上有包含复选框的控件,并且还需要知道如何递归地包含这些复选框,请添加评论,我将编辑代码。否则,这应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2018-04-21
      • 2012-06-10
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多