如何从MS Access数据库中检索性别值?
这是我的代码:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
myconnection = New OleDbConnection(StrConn)
myconnection.Open()
Dim str As String
str = "SELECT * FROM register WHERE (MatricNum = '" & txtSearch.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myconnection)
dr = cmd.ExecuteReader
While dr.Read()
txtMatricnum.Text = dr("MatricNum").ToString
txtFname.Text = dr("Fname").ToString
txtLname.Text = dr("Lname").ToString
rbtMale .Text or rbtfemale.Text = dr("Gender").ToString
DateTimePicker1.Value = dr("DOB").ToString
txtlevel.Text = dr("Level").ToString
txtFaculty.Text = dr("Faculty").ToString
txtDapartment.Text = dr("Department").ToString
txtContact.Text = dr("Contact").ToString
txtState.Text = dr("State").ToString
txtLGA.Text = dr("LGA").ToString
txtAddress.Text = dr("Address").ToString
Try
Dim data As Byte() = DirectCast(dr("Picture"), Byte())
Dim ms As New IO.MemoryStream(data)
PictureBox1.Image = Image.FromStream(ms)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End While
myconnection.Close()
End Sub
答案 0 :(得分:0)
此代码并未执行您希望的操作:
rbtMale .Text or rbtfemale.Text = dr("Gender").ToString
假设您在数据库中存储的值是 Male 和 Female ,您可以考虑使用简单的Select Case语句:
Select Case dr("Gender").ToString
Case "Female"
rbtFemale.Checked = True
Case "Male"
rbtMale.Checked = True
End Select
我已经针对Select Case
陈述发表If
声明,对我而言,它读得更好,但要么就足够了。我相信有一个ISO标准,我从阅读question:
ISO / IEC 5218中规定的四个代码是:
0 =未知,
1 =男性,
2 =女性,
9 =不适用。
您可能需要考虑进一步阅读此内容,以便将其包含在内以供参考。
我还想指出你应该强烈使用参数。有关原因的详细信息,请参阅Bobby Tables。
以下是一个例子:
cmd.Parameters.Add("@MatricNum", OleDbType.VarChar).Value = txtSearch.Text
您还应该考虑实施Using:
有时,您的代码需要非托管资源,例如文件句柄,COM包装器或SQL连接。使用块可确保在代码完成后处理一个或多个此类资源。这使得它们可供其他代码使用。
以下是一个例子:
Using con As New OleDbConnection(StrConn),
cmd As New OleDbCommand("SELECT * FROM [register] WHERE [MatricNum] = ?", con)
End Using
所有代码看起来都像这样:
Using con As New OleDbConnection(StrConn),
cmd As New OleDbCommand("SELECT * FROM [register] WHERE [MatricNum] = ?", con)
con.Open()
cmd.Parameters.Add("@MatricNum", OleDbType.VarChar).Value = txtSearch.Text
dr = cmd.ExecuteReader
While dr.Read()
txtMatricnum.Text = dr("MatricNum").ToString
txtFname.Text = dr("Fname").ToString
txtLname.Text = dr("Lname").ToString
Select Case dr("Gender").ToString
Case "Female"
rbtFemale.Checked = True
Case "Male"
rbtMale.Checked = True
End Select
DateTimePicker1.Value = dr("DOB").ToString
txtlevel.Text = dr("Level").ToString
txtFaculty.Text = dr("Faculty").ToString
txtDapartment.Text = dr("Department").ToString
txtContact.Text = dr("Contact").ToString
txtState.Text = dr("State").ToString
txtLGA.Text = dr("LGA").ToString
txtAddress.Text = dr("Address").ToString
Try
Dim data As Byte() = DirectCast(dr("Picture"), Byte())
Dim ms As New IO.MemoryStream(data)
PictureBox1.Image = Image.FromStream(ms)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End While
End Using