循环复选框并将复选框值插入DB

时间:2012-04-14 04:28:14

标签: c# asp.net vb.net

ASPX页面

<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

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

2 个答案:

答案 0 :(得分:0)

你只是在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中的代码

答案 1 :(得分:0)

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