0

I am trying to retrieve the information from a database table using SqlDataReader. I have two columns one string and the other is bit. The string will be filled in a textbox. But the problem with the bit when I wanted to fill it on a radiobuttonlist it doesn't happen. It keep giving me this error Specified cast is not valid. This is my vb server side code:

Dim dt As DataTable = New DataTable()
        Dim command As New SqlCommand(query2, conn)
        Dim param As New SqlParameter()
        param.ParameterName = "@cUserName"
        param.Value = Session("Edit")
        command.Parameters.Add(param)

        Dim dr As SqlDataReader = command.ExecuteReader()
        If dr.HasRows Then
            dr.Read()
            tbUsername.Text = dr.GetString(0)
            rblDept.SelectedIndex = dr.GetByte(1)
        End If

I tried dr.GetByte(1) but it doesn't work. Help me please.

9
  • Have you tried Convert.ToInt32(dr.GetByte(1)) or possible CInt()? Commented Mar 19, 2013 at 4:56
  • Come to think of it, as far as I know a column with bit value is binary, storing either 0 or 1 (or null in which case you might have a problem). You should just be able to do CInt(dr(1)) and it should work. Commented Mar 19, 2013 at 5:00
  • @yu_ominae yeah i tried it and it gives me the same error! Commented Mar 19, 2013 at 5:10
  • @yu_ominae i tried CInt(dr(1)) it retrieves only when then value is 0. Doesn't make sense Commented Mar 19, 2013 at 5:10
  • @yu_ominae i just tried to put it in a label and i am surprised why it gives me -1 when the value is false. what shell i do? Commented Mar 19, 2013 at 5:15

1 Answer 1

0

I did something silly and it works. The code is:

If dr.HasRows Then
            dr.Read()
            tbUsername.Text = dr.GetString(0)
            Dim deptid As Integer = CInt(dr(1))
            If deptid = -1 Then
                rblDept.SelectedIndex = 1
            Else
                rblDept.SelectedIndex = 0
            End If
        End If

It works perfect.

Thanks all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.