循环检查复选框并将复选框值插入数据库

本文关键字:复选框 插入 数据库 检查 循环 | 更新日期: 2023-09-27 18:31:00

ASPX Page:

<asp:ListView ID="lvSubjects" runat="server" >
        <LayoutTemplate>
        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
        </LayoutTemplate>
        <ItemTemplate>
            <asp:CheckBox ID="cbRegularSubjects" Text=<%# Eval("SubjectName") %> runat="server" />
        </ItemTemplate>

        <AlternatingItemTemplate>
        <asp:CheckBox ID="cbRegularSubjects" Text=<%# Eval("SubjectName") %> runat="server" />
        </AlternatingItemTemplate>
        </asp:ListView>

代码隐藏:

For Each ctrl As Control In Page.Controls
            If TypeOf ctrl Is CheckBox AndAlso CType(ctrl, CheckBox).Checked Then
                '**Here I want to get the text of the check box and insert into the DB**
            End If

       Next

我哪里出错了??我没有收到任何错误...但是这段代码对我不起作用。

循环检查复选框并将复选框值插入数据库

For i As Integer = 0 To lvSubjects.Items.Count - 1
            Dim coll As ControlCollection = lvSubjects.Items(i).Controls
            For Each c As Control In coll
                If TypeOf c Is CheckBox Then
                    Dim box As CheckBox = CType(c, CheckBox)
                    If box.Checked Then
                        MsgBox(box.Text)
                    End If
                End If
            Next c
        Next i

您只在Page.Controls中搜索,而您的复选框在页面控件层次结构中更深。

foreach (ListViewItem row in listView.Rows)
{
  if (row.ItemType == ListViewItemType.DataItem)
  {
    CheckBox chk = row.FindControl("Checkboxid");
    if  (chk.Checked)
    {
     //Write code to store this checkbox value to database here
    }
   }
  }

请使用正确的控件名称更改 VB 中的代码