如何检查复选框列表中的选定项目(从代码生成)

时间:2016-03-17 08:33:00

标签: asp.net vb.net checkboxlist

我有一个ASP.NET / VB应用程序 我需要选中复选框列表中的选定项目,但复选框是动态来自代码

<asp:Panel ID="panel1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Save" />
    <asp:Label ID="lbl_Selected_Items" runat="server" Text=""></asp:Label>
</asp:Panel>

代码背后 页面加载

Dim CheckBoxList As New CheckBoxList
            pagerview.Controls.Add(CheckBoxList)
            ...est

Button1点击事件

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CheckBoxList1 As CheckBoxList = CType(Me.FindControl("CheckBoxList"), CheckBoxList)
Dim sCheckedValue As String = ""
For Each oItem As ListItem In CheckBoxList1.Items
    If oItem.Selected Then
        If sCheckedValue = "" Then
            sCheckedValue = ("Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
        Else
            sCheckedValue += ("<br/>Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
        End If
    End If
Next
lbl_Selected_Items.Text = sCheckedValue

错误文本:null引用异常对象引用未设置为对象的实例 -   Error

1 个答案:

答案 0 :(得分:-1)

那发生了什么?错误?没结果?

此时我唯一可以推荐的是在页面init中加载动态控件而不是页面加载。

修改

当您调试时,您会发现按钮单击的第一行上的复选框是Nothing。你的代码中有两个错误。

  1. 将控件添加到表单时,不提供id值。而且你没有查找这个值

  2. 在按钮中查找控件时,单击FindControl仅查找单个容器。它不是递归的。你应该调用pagerView.FindControl

  3. 页面加载(我仍然建议使用init):

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Handles Me.Load
        Dim CheckBoxList As New CheckBoxList
        CheckBoxList.ID = "cbl1"
        pagerview.Controls.Add(CheckBoxList)
    End Sub
    

    点击按钮:

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim CheckBoxList1 As CheckBoxList = CType(pagerview.FindControl("cbl1"), CheckBoxList)
        Dim sCheckedValue As String = ""
        For Each oItem As ListItem In CheckBoxList1.Items
            If oItem.Selected Then
                If sCheckedValue = "" Then
                    sCheckedValue = ("Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
                Else
                    sCheckedValue += ("<br/>Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
                End If
            End If
        Next
        lbl_Selected_Items.Text = sCheckedValue
    End Sub
    

    MS Reference