简体   繁体   中英

How to get the Data in the database to mu UI form using Connection string in Vb.Net

I am using a Combobox and I need to fill the data from my sql server database using connection string.

What I have Tried:

Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Xml
Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports System.Configuration


Public Class Form1

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim VB = ConfigurationManager.ConnectionString["HMDB"].ConnectionString
        Using Con = New SqlConnection(VB)
            Dim SqlText = "Select DocEntry from dbo.Master1"
            Dim cmd = New SqlCommand(SqlText, Con)
            Con.Open()
            ComboBox1.DataSource = cmd.ExecuteReader()
            ComboBox1.DataBind()

        End Using
    End Sub
End Class

App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configuration>
    <connectionStrings>
      <add name ="HMDB"
           connectionString ="Data Source=DESKTOP-68VGRJG;Database=master;integrated security =SSPI"/>
            </connectionStrings>
</configuration>
</configuration> 

I don't know where I have made a mistake. I need to call the data in sql server to the combo box and I have to make it visible.

You may want to populate your comboBox once your form is loaded, not on the change to comboBox event.

Write the same code in Form1() constructor.

public Form1()
        {
            InitializeComponent();
             Dim VB = ConfigurationManager.ConnectionString["HMDB"].ConnectionString
            Using Con = New SqlConnection(VB)
            Dim SqlText = "Select DocEntry from dbo.Master1"
            Dim cmd = New SqlCommand(SqlText, Con)
            Con.Open()
            ComboBox1.DataSource = cmd.ExecuteReader()
            ComboBox1.DataBind()
            End Using           
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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