Programming for Everybody: Retrieve data from a database in VB.net and Solve Invalid attempt to read when no data is present

Retrieve data from a database in VB.net and Solve Invalid attempt to read when no data is present


 

Imports System.Data.SqlClient

Public Class Form3

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con1 As SqlConnection = New SqlConnection("Data Source=.;Initial Catalog=names;Integrated Security=True")
        con1.Open()
        Dim cmd1 As New SqlCommand(" Select name1,tel from table1 where id=@parm1", con1)

        cmd1.Parameters.AddWithValue("@parm1", TextBox1.Text)

        Dim myreader As SqlDataReader

        myreader = cmd1.ExecuteReader()

        If (myreader.Read()) Then
            TextBox2.Text = myreader("name1")
            TextBox3.Text = myreader("tel")
        Else
            TextBox2.Text = ""
            TextBox3.Text = ""
            MessageBox.Show("No Data Found")
        End If
       

        con1.Close()


    End Sub

No comments:

Post a Comment