Kevin
Kevin

Reputation: 107

Unable to connect to SQL Server database from VB.NET

I am using Visual Studio 2022 (VB.Net) and SQL Server 2022 Express. I am not a programmer; I just like teaching myself coding and trying to learn.

I have a program, and I am trying to access the data in the table I created, but when I try to connect a DataGrid view to the table there is nothing there. See the screenshots.

If someone could give me a hint, it would be greatly appreciated.

enter image description here

Upvotes: -1

Views: 174

Answers (1)

Konstantin Makarov
Konstantin Makarov

Reputation: 1376

SQL Server

Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Using connection As New SqlConnection(
            "Server=localhost\SQLEXPRESS;" &
            "Database=master;" &
            "Trusted_Connection=True;")

            Dim adapter As New SqlDataAdapter("select * from spt_values", connection)
            Dim table As New DataTable
            adapter.Fill(table)
            DataGridView1.DataSource = table

        End Using

    End Sub
End Class

MySQL

Imports MySql.Data.MySqlClient

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Using connection As New MySqlConnection(
            "server=localhost;" &
            "port=3306;" &
            "database=sakila;" &
            "user=root;" &
            "password=********;")

            Dim adapter As New MySqlDataAdapter("select * from city", connection)
            Dim table As New DataTable
            adapter.Fill(table)
            DataGridView1.DataSource = table

        End Using

    End Sub
End Class

Upvotes: 0

Related Questions