Retrieving a bit column from sql database in VB NET
I have encountered a problem where in my database I have a column that is a bit either 0 or 1 specifying if a user is an admin or is account suspended or not. And in my VB code I am trying to retrieve that bit. Example code:
Dim dtRequests As DataTable
dtRequests = New DataTable("Users")
dtRequests.Columns.Add("SESLoginID", System.Type.GetType("System.Int32"))
dtRequests.Columns.Add("fullname", System.Type.GetType("System.String"))
dtRequests.Columns.Add("SESSuspended", System.Type.GetType("System.Byte"))
dtRequests.Columns.Add("SESAdmin", System.Type.GetType("System.Byte"))
dtRequests.Columns.Add("OfficeName", System.Type.GetType("System.String"))
cmdoledb = New SqlCommand("SELECT SESLoginID, SESFirstName + ' ' + SESLastName As fullname , SESSuspended, SESAdmin, OfficeID from SESLogin where (SESEmail Like '%" & keyword & "%' or SESFirstName + ' ' + SESLastName like '%" & keyword & "%' or SESLastName like '%" & keyword & "%') order by SESFirstName;", objConnect)
cmdoledb.Parameters.AddWithValue("@pid", pid)
objConnect.Open()
Dim rdr As SqlDataReader
Dim myItem As ListItem = New ListItem()
rdr = cmdoledb.ExecuteReader()
While rdr.Read()
Dim newrow As DataRow
newrow = dtRequests.NewRow
newrow.Item("SESLoginID") = rdr.GetInt32(0)
newrow.Item("fullname") = rdr.GetString(1)
newrow.Item("SESSuspended") = rdr.Ge开发者_开发问答tByte(2) // Specified cast is not valid.
newrow.Item("SESAdmin") = rdr.GetByte(3) // Specified cast is not valid.
Dim officeid As Integer = rdr.GetInt32(4)
Dim officename As String = ""
cmdldb = New SqlCommand("SELECT OfficeName from Office where OfficeID = @offid", objConnected)
cmdldb.Parameters.AddWithValue("@offid", officeid)
objConnected.Open()
officename = cmdldb.ExecuteScalar()
newrow.Item("OfficeName") = officeid
objConnected.Close()
dtRequests.Rows.Add(newrow)
End While
I tried getting rdr.GetByte(3), this tells me cast not valid, but there is no function of which will say GetBit, and if such exists I could not find it. Thus Im hoping for a quick response.
Try rdr.GetBoolean(3)
to get Bit values. A bit in SQL Server is the same as a boolean in VB, except it uses 1 and 0 instead of true and false.
Use GetBoolean
Although there is no "boolean" SQL data type, bit maps to .net boolean
You want
newrow.Item("SESSuspended") = rdr.GetBoolean(2)
newrow.Item("SESAdmin") = rdr.GetBoolean(3)
You should also change these lines
dtRequests.Columns.Add("SESSuspended", System.Type.GetType("System.Byte"))
dtRequests.Columns.Add("SESAdmin", System.Type.GetType("System.Byte"))
to
dtRequests.Columns.Add("SESSuspended", System.Type.GetType("System.Boolean"))
dtRequests.Columns.Add("SESAdmin", System.Type.GetType("System.Boolean"))
You can specify the name of the Data Item rather than the index. Such as:
newrow.Item("SESSuspended") = rdr("SESSuspended")
精彩评论