vb.net中无法绑定多部分标识符“ System.Data.DataRowView”

时间:2018-11-16 19:46:54

标签: sql-server vb.net

我做了两个组合框。其中之一取决于另一方的数据。当第一个选定索引更改时,我需要使用新值并使用它来更新另一个。这是我到目前为止第一个组合框的内容:

Try
    Dim cmd As New SqlCommand("select * from tb_section ", connSql)

    connSql.Open()

    Dim dr As New SqlDataAdapter(cmd)
    Dim table As New DataTable
    dr.Fill(table)

    compsec.DataSource = table
    compsec.DisplayMember = "sec_name"
    compsec.ValueMember = "sec_code"

Catch ex As Exception

    MsgBox(ex.Message)
    connSql.Close()

Finally
    connSql.Close()

End Try

这是另一个组合框的代码:

Public Sub all_group_list(sectioncode)

    Try
        Dim cmd As New SqlCommand("select * from tb_group where sec_code= " & sectioncode.ToString, connSql)

        connSql.Open()

        Dim dro As New SqlDataAdapter(cmd)
        Dim table As New DataTable
        dro.Fill(table)

        compgroup.DataSource = table
        compgroup.DisplayMember = "group_name"
        compgroup.ValueMember = "group_code"

    Catch ex As Exception

        MsgBox(ex.Message)
        connSql.Close()

    Finally
        connSql.Close()

    End Try
End Sub

当第一个组合框索引更改时,我运行以下代码:

 Private Sub compsec_SelectedIndexChanged(sender As Object, e As EventArgs) Handles compsec.SelectedIndexChanged

    connSql.Close()

    all_group_list(compsec.SelectedValue.ToString)
End Sub

1 个答案:

答案 0 :(得分:0)

目前尚不清楚您实际上遇到什么问题,但是下面的代码中有一些修复程序。名称:请勿使用字符串串联将数据放入SQL命令!此外,请勿尝试在整个应用程序中重复使用同一连接对象。仅共享连接字符串,因为共享相同的连接对象会干扰ADO.Net中的连接池功能。此外,DataAdapter将为您处理打开和关闭连接,并且如果抛出异常,则Using块而不是Finally块是确保连接关闭的最佳方法。 / p>

Try
    Dim ds As New DataSet
    Using cn As new SqlConnection(connSql.ConnectionString), _
          cmd As New SqlCommand("select sec_name, sec_code from tb_section", cn), _
          da As New SqlDataAdapter(cmd)
        da.Fill(ds)
    End Using

    compsec.DisplayMember = "sec_name"
    compsec.ValueMember = "sec_code"
    compsec.DataSource = ds.Tables(0)
Catch ex As Exception
    MsgBox(ex.Message)
End Try

Public Sub all_group_list(sectioncode)
    Try
        Dim ds As New DataSet
        Using cn As New SqlConnection(connSql.ConnectionString), _
              cmd As New SqlCommand("select group_name, group_code from tb_group where sec_code= @SectionCode", cn), _
              da As New SqlDataAdapter(cmd)
            'Had to guess at column type/length here. Use the actual column definition from your database
            cmd.Parameters.Add("@SectionCode", SqlDbType.NVarChar, 10).Value = sectioncode
            da.Fill(ds)
        End Using

        compgroup.DisplayMember = "group_name"
        compgroup.ValueMember = "group_code"
        compgroup.DataSource = ds.Tables(0)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Private Sub compsec_SelectedIndexChanged(sender As Object, e As EventArgs) Handles compsec.SelectedIndexChanged
    all_group_list(compsec.SelectedValue.ToString())
End Sub