2 Replies - 797 Views - Last Post: 18 December 2016 - 02:52 AM Rate Topic: -----

#1 u12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 17-December 16

Cannot read when data is not present

Posted 17 December 2016 - 11:01 PM

Hi everyone!My form in visual studio is made to enter data in sql server. The problem is when i run this code, msgbox for idprevious shows me that 'cannot read when data is not present'. But data is present because when I run cmd1 in sql itself, it shows me the value of the last row. I want to access the value of the last row and then in my form I want to show that value incremented by one in txtid.
Please help!

Public Class Form1

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        Dim cmd1 As New SqlCommand
        Dim qstring As SqlDataReader
        Dim qprevious As Integer
        Try
            con.ConnectionString = "Persist Security Info=False;User ID=;Password=;Initial Catalog=mydb;Server=user12"
            cmd.CommandType = System.Data.CommandType.Text
            
            cmd1.CommandText = "select top 1 id from Table1 order by id desc"

            cmd.CommandText = "insert into Table values(@fname, @lname, @id)"
            cmd.Parameters.Add("@fname", SqlDbType.NChar).Value = Me.txtfname.Text
            cmd.Parameters.Add("@lname", SqlDbType.NChar).Value = Me.txtlname.Text
            cmd.Parameters.Add("@id", SqlDbType.Int).Value = Me.txtid.Text

            cmd.Connection = con
            cmd1.Connection = con
            con.Open()

            cmd.ExecuteNonQuery()
            idstring = cmd1.ExecuteReader()
            idprevious = idstring.Item("id")

            MsgBox(idprevious)
            MsgBox("Successfully Added")
            Me.txtfname.Text = ""
            Me.txtlname.Text = ""
            txtfname.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            con.Close()
        End Try
    End Sub
End Class


Is This A Good Question/Topic? 0
  • +

Replies To: Cannot read when data is not present

#2 u12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 17-December 16

Re: Cannot read when data is not present

Posted 17 December 2016 - 11:30 PM

I solved it! I forgot to write idstring.Read()
Now it works! Thank You everyone :)
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw  Icon User is offline

  • lashings of ginger beer
  • member icon

Reputation: 6342
  • View blog
  • Posts: 25,594
  • Joined: 12-December 12

Re: Cannot read when data is not present

Posted 18 December 2016 - 02:52 AM

Glad you sorted.

Topic moved to VB.NET forum. Note that your question involves MS SQL Server, not MySQL.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1