【问题标题】:VB.NET display datagridview with SQL Server databaseVB.NET 用 SQL Server 数据库显示 datagridview
【发布时间】:2023-03-28 10:25:01
【问题描述】:

我是 VB.NET 的新手,我想连接到本地 SQL Server。我只是无法连接,希望有人能修复我的代码。

Public Class Main_Tr

    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim connectionString As String = "Data Source=IHOMISSERVER;Initial Catalog=homis;User ID=sa;Initial Catalog=pubs;Integrated Security=True"
        Dim sql As String = "SELECT * FROM table_name"
        Dim connection As New SqlConnection(connectionString)
        Dim dataadapter As New SqlDataAdapter(sql, connection)
        Dim ds As New DataSet()
        connection.Open()
        dataadapter.Fill(ds, "column_name")
        connection.Close()
        DataGridView1.DataSource = ds
        DataGridView1.DataMember = "column_name"
    End Sub

    Private Sub Main_Tr_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

End Class

【问题讨论】:

  • 您在连接字符串中设置了两次初始目录值。您要连接的数据库的名称是什么?此外,您还没有指定数据库实例,只是服务器。当我连接到本地数据库时,我使用 (LocalDB)\MSSQLLocalDB

标签: sql-server database vb.net


【解决方案1】:

你不需要:

connection.open 
connection.close

现在使用这个:

  dim con as new connectionstring='your connection string

  dim cmd as new sqlcommand("Select * from [table name-remove brackets if required]",con)

  dim adapter as new sqldataadapter(cmd)

  Dim table as new datatable

  adapter.fill(table)

  datagridview1.datasource=table

【讨论】:

  • 如果对您有帮助,请务必将答案标记为答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
相关资源
最近更新 更多