vb.net VB.NET用SQL Server数据库显示datagridview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47447273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:21:41 来源:igfitidea点击:
VB.NET display datagridview with SQL Server database
提问by a.baldivia
I am new to VB.NET, I would like to connect to a local SQL Server. I just can't connect, hope someone will fix my code.
我是 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
采纳答案by Aousaf rashid
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

