Search code examples
vb.netfindcontrolhiddenfield

Unable to cast HiddenField to I.Convertible


I have 2 DataLists where one is nested in the other one. I have one line (Dim QID....) that keeps giving me problems, no matter what combination of code I can find online. I just want to be able to get the Hidden Field to show up as an integer so that my If statement will work.

Dim dl2 As DataList = CType(e.Item.FindControl("DataList2"), DataList)
        Dim QID As Integer = Convert.ToInt32(e.Item.FindControl("HiddenField2"))
        If QID = 33 Then
                Dim lbl As Label = dl2.FindControl("Label3")
                For Each i As ListItem In dl2.Items
                    If lbl.Text = "Self Directed" Or lbl.Text = "Systems" Then
                        lbl.Visible = False
                    End If
                Next
        End If

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" 
 Width="100%" CellPadding="4" ForeColor="#333333">
<ItemTemplate>
<asp:HiddenField ID="HiddenField2" runat="server" 
 Value='<%# Eval("QuestionID") %>'></asp:HiddenField>
<asp:Label ID="lblQuesNum" runat="server" Font-Bold="True" 
 Text='<%# Eval("QuestionNum") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Font-Bold="True" 
 Text='<%# Eval("Question") %>'></asp:Label>
<asp:HiddenField ID="hiddenPicklistID" runat="server"  
 Value='<%# Eval("PicklistID") %>' />
<asp:HiddenField ID="HiddenField1" runat="server" 
 Value='<%# Eval("AnswerType") %>' />

<asp:DataList ID="DataList2" runat="server" DataSourceID="dsPicklist">
<ItemTemplate>
    <asp:HiddenField ID="hidPickID" runat="server" value='<%# Eval("PICKLISTID") %>' />
    <asp:Label ID="Label3" runat="server" Text='<%# Eval("TEXT") %>'></asp:Label> 
    <asp:HiddenField ID="HiddenField1" runat="server" 
     Value='<%# Eval("AnswerType") %>' />
 </ItemTemplate>
 </asp:DataList>
 </asp:TextBox>

Solution

  • You cannot cast a control to a numeric value. Actually you want the value of the Hiddenfield to be casted to an integer.

    Dim hidden2 = DirectCast(e.Item.FindControl("HiddenField2"), HiddenField)
    Dim QID As Integer = Int32.Parse(hidden2.Value)