【问题标题】:how to retrieve multiple selected value from asp:checkbox .net c#如何从asp中检索多个选定的值:checkbox .net c#
【发布时间】:2011-09-23 07:01:36
【问题描述】:

有谁知道如何从 asp:checkbox .net c# 中检索多个选定的值?

示例: 我是 .net c# 的新手,我有以下代码,但我不知道如何从 .net c# 中检索多个选定值

<tr>   
    <th class="graytext r">Add Test:</th>
    <td>
        <asp:CheckBoxList ID="Test" runat="server" DataSourceID="dsTest" CssClass=""
            DataValueField="employeeid" DataTextField="fullname" 
            AppendDataBoundItems="false" >
            <asp:ListItem></asp:ListItem>
        </asp:CheckBoxList>  
        <asp:SqlDataSource ID="dsTest" runat="server" 
            ConnectionString="<%$ ConnectionStrings:SmartStaffConnectionString %>"
            SelectCommand="app_dsTest_select" SelectCommandType="StoredProcedure">
        </asp:SqlDataSource>
    </td>
</tr>  

【问题讨论】:

  • 您是在寻找选定的项目还是选中的项目??
  • @Akram Shahda CheckBoxList 也是如此

标签: c# asp.net .net webforms


【解决方案1】:

使用以下内容:

for (int i=0; i<checkboxlist1.Items.Count; i++)
{
    if (checkboxlist1.Items[i].Selected)
    {
        Message.Text += checkboxlist1.Items[i].Text + "<br />";
    }
}

请参阅CheckBoxList Class

【讨论】:

【解决方案2】:

可能最简单的方法是这样的:

foreach (ListItem item in myCheckboxList.Items)
{
  if (item.Selected)
  {
    // do something with this item
  }
}

【讨论】:

    【解决方案3】:

    这是一个旧线程,但使用 .NET 4.5(不确定以前的版本是否有效),您可以使用 LINQ 来执行此操作:

    IEnumerable<ListItem> selectedItems = myCheckboxList.Items.Cast<ListItem>().Where(x => x.Selected);
    

    【讨论】:

      【解决方案4】:

      像我在下面那样尝试 listitem.Selected 属性

      protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
      {
          Label1.Text = string.Empty;
      
          foreach (ListItem listitem in CheckBoxList1.Items)
          {
              if (listitem.Selected)
                  Label1.Text += listitem.Text + "<br />";
          }
      }
      

      【讨论】:

        【解决方案5】:
        foreach (ListItem item in myCheckboxList.Items)
        {
          if (item.Selected)
          {
            //Your code goes here
          }
        }
        

        【讨论】:

        • CheckboxList 没有属性SelectedItems,有一个名为SelectedItem(单数)的属性,但它只返回第一个选定的项目。
        • @Bazz - 但是 ListBox 也有 CheckListBox。查看此链接,msdn.microsoft.com/en-us/library/…
        • 很抱歉让您失望了,但是您的参考是针对 winforms,OP 使用的是 asp.net msdn.microsoft.com/en-us/library/…
        【解决方案6】:

        您必须遍历Items

        请参阅CheckBoxList Class

        要确定检查了哪些项目,请遍历集合并测试列表中每个项目的Selected 属性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-11
          • 1970-01-01
          • 2019-11-23
          相关资源
          最近更新 更多