Bind dataset with label control in VB.NET

Here we see how to use ado.net to connect to a database and binding DataSet with the Label control.
  • 5220
Download Files:
 

Creating connection object

To create a connection we pass the connection string as a parameter in connection object.

Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

Dim con As New SqlConnection(str)

 

The above string defines the connection string which is used to connect the database with the application.

 

Now we create a database table and insert some values in this table. Table looks like this.

 

create table logn

(

username varchar(50),

password varchar(40)

)

go

insert into logn values('monu','mohan')

go

insert into logn values('Rohatash','rohit')

go

insert into logn values('Manoj','singh')

go

select * from logn;

The table looks like this.
 

table-in-vb.net.gif  


Data set Bind to Label

 

To bind DataSet with the label use DataBindings property to bind the control. The below line show the Data binding with Label control.

 

Label1.DataBindings.Add("text", dataset1, "logn.username")

 

For example

 

Drag and drop two Label control on the form. The form looks like this.
 

form-in-vb.net.gif
 

 

Now double click on the form load and add the following code.

 

Imports System.Data.SqlClient

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

        Dim con As New SqlConnection(str)

        Dim str1 As String = "SELECT * FROM logn"

        Dim da As New SqlDataAdapter(str1, con)

        Dim dataset1 As New DataSet()

        da.Fill(dataset1, "logn")

        ' Bind Label1 to username column of the logn table

        Label1.DataBindings.Add("text", dataset1, "logn.username")

        ' Bind Label2 to password column of the logn table

        Label2.DataBindings.Add("text", dataset1, "logn.password")

    End Sub

End Class

 

Now run the application and test it.

show-output-vb.net.gif
 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.