在datagridview中打开SQL Server MDF文件

时间:2017-05-03 23:57:01

标签: sql-server vb.net datagridview

我是Visual Basic的新手,我正在上一学期学习Visual Basic课程以获得乐趣。我无法使用datagridview连接到我的教师给我的.MDF SQL Server数据库文件。我在sConnection.ConnectionString =“”上收到一个空的异常错误,而且我对这个错误。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    sConnection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jkome\Desktop\Kayaks.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
    sConnection.Open()

    sCommand.CommandText = "Select * from KayakTypes;"
    sReader = sCommand.ExecuteReader()
    sTable.Load(sReader)
    DGVkyaks.DataSource = sTable

1 个答案:

答案 0 :(得分:0)

试试这个

Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sTable As New DataTable
        Dim connectionString As String =
            <Text>
                Data Source=(LocalDB)\v11.0;
                AttachDbFilename=C:\Users\Jkome\Desktop\CustomerDatabase.mdf;
                Integrated Security=True;
                Connect Timeout=30
            </Text>.Value

        Using cn As New SqlConnection With {.ConnectionString = connectionString}
            Using cmd As New SqlCommand With
                {
                    .CommandText = "Select * from KayakTypes",
                    .Connection = cn
                }

                cn.Open()
                sTable.Load(cmd.ExecuteReader)

            End Using
        End Using

        DGVkyaks.DataSource = sTable

    End Sub
End Class