通过选择组合框中的项目将多个数据从sql绑定到标签

时间:2013-03-26 19:39:04

标签: sql-server vb.net visual-studio-2010 visual-studio sql-server-2008

如果我在组合框中选择一个来自sql的项目,我将如何将多个数据从sql绑定到标签:这是我的代码:

    Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged

    If cmboCourse.Text = "ADVANCED COMPUTER TECHNICIAN" Then
        callMe()
    ElseIf cmboCourse.Text = "AUTOELECTRICITY" Then
        callMe()
    ElseIf cmboCourse.Text = "AUTOMOTIVE" Then
        callMe()
    End If

End Sub


Private Sub callMe()

Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "course")
lbl.DataBindings.Add("text", dataset1, "course.Course_Code")

end sub

这是我的表

 Course_Code      Course
 ACT              ADVANCED COMPUTER TECHNICIAN
 AE               AUTOELECTRICITY
 AM               AUTOMOTIVE

它只绑定一个数据,我想绑定特定列中的许多数据示例我在组合框中选择一个课程AUTOMOTIVE如何将AUTOMOTIVE的course_code绑定到标签,如果我选择AUTOELECTRICITY如何将AUTOELECTRICITY的course_code绑定到同一个标签

2 个答案:

答案 0 :(得分:0)

未经测试,如果不起作用,请告诉我。

Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
    callMe(cmboCourse.Text)
End Sub


Private Sub callMe(ByVal course as String)

    Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
    Dim con As New SqlConnection(str)
    Dim str1 As String = "SELECT * FROM tbl_course WHERE [Course]='" & course & "'"
    Dim da As New SqlDataAdapter(str1, con)
    Dim dataset1 As New DataSet()
    da.Fill(dataset1, "tbl_course")
    'lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
    If dataset1.Tables("tbl_course").Rows.Count > 0 Then
        lbl.Text = dataset1.Tables("tbl_course").Rows(0)("Course_Code")
    Else
        MsgBox "Course [" & course & "] not found"
    End If

End Sub

请注意,在您的代码da.Fill(dataset1, "course")中,您将表指定为'course',而select语句则从'tbl_course'表中选择。我假设后者是正确的名称。

编辑1:

错误修复

编辑2:

调试

答案 1 :(得分:0)

sc.Open()         Dim da As New SqlDataAdapter()

    Dim dataset1 As New DataSet()
    Dim sql As New SqlCommand("Select * from book where Title='" + cmbtit.Text + "'", sc)

    da.SelectCommand = sql
    da.SelectCommand.ExecuteNonQuery()
    da.Fill(dataset1, "book")

    If dataset1.Tables("book").Rows.Count > 0 Then
        txtauthor.Text = dataset1.Tables("book").Rows(0)("Author")
    Else
        MsgBox("Author [" & cmbtit.Text & "] not found")
    End If
    sc.Close()

End Sub