简体   繁体   English

VB.NET使用SQL Server数据库显示datagridview

[英]VB.NET display datagridview with SQL Server database

I am new to VB.NET, I would like to connect to a local SQL Server. 我是VB.NET的新手,我想连接到本地SQL Server。 I just can't connect, hope someone will fix my code. 我无法连接,希望有人可以修复我的代码。

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

You don't need : 您不需要:

connection.open 
connection.close

Now use this : 现在使用这个:

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM