使用基于主键入口到另一个文本框的数据库数据自动填充文本框

时间:2015-04-14 08:16:41

标签: vb.net

我有下面的代码,它工作正常,但每当我插入表中不存在的学号时,其余的文本框将继续显示上一个现有条目的数据。即使我删除了学生编号文本框中的所有内容,也会发生这种情况。 我如何更改它,以便在学生编号文本框为空或包含数据库中不存在的学号时,清除其余文本框? 提前谢谢。

    '  Try

    Dim mycommand As SqlCommand = New SqlCommand()

    Dim datareader As SqlDataReader = Nothing

    myconnection.Open()

    Dim query As String

    query = " select StudentNo,Fullname,Year,Term,Class from StudentRegistration  where StudentNo = '" & TxtStudentNo.Text & "' and (class = 'Senior 5A' or Class ='Senior 5S' or Class='Senior 6A' or class='Senior1 6S')"
    mycommand = New SqlCommand(query, myconnection)
    datareader = mycommand.ExecuteReader()
    While datareader.Read
        If datareader IsNot Nothing Then
            '    TxtStudentNo.Text = datareader.Item("StudentNo")
            TxtName.Text = datareader.Item("FullName")
            TxtYear.Text = datareader.Item("Year")
            TxtTerm.Text = datareader.Item("Term")
            TxtClass.Text = datareader.Item("Class")
        End If

    End While
    myconnection.Close()
    ' Catch ex As Exception
    'MessageBox.Show(ex.Message)
    ' End Try`

2 个答案:

答案 0 :(得分:0)

向阅读器添加else条件并清除该模块中的文本框。

 While datareader.Read
        If datareader IsNot Nothing Then
            '    TxtStudentNo.Text = datareader.Item("StudentNo")
            TxtName.Text = datareader.Item("FullName")
            TxtYear.Text = datareader.Item("Year")
            TxtTerm.Text = datareader.Item("Term")
            TxtClass.Text = datareader.Item("Class")
        else 
            TxtName.Text = ""
            TxtYear.Text = ""
            TxtTerm.Text = ""
            TxtClass.Text = ""
        End If

希望没有比这更重要的了。

答案 1 :(得分:0)

我最终将我的代码更改为下面的代码,它正是我想要的。

    Private Sub getData()
       Dim dt As New DataTable()
    myconnection.Open()

    Dim Mycommand As New SqlCommand("select Fullname,Year,Term,Class from StudentRegistration  where StudentNo = '" & TxtStudentNo.Text & "'", myconnection)
    Dim sqlDa As New SqlDataAdapter(Mycommand)
    sqlDa.Fill(dt)
    If dt.Rows.Count > 0 Then
        TxtName.Text = dt.Rows(0)("FullName").ToString()
        TxtYear.Text = dt.Rows(0)("Year").ToString()
    Else
        TxtName.Text = ""
        TxtYear.Text = ""
    End If
    myconnection.Close()
End Sub