Can not found Row 0 in vb.NET

I try to select the first row and first item from my SQL
But, it show me message “Can not found Row 0 ”

 sqlCmd1 = "SELECT Type.Name FROM Type INNER JOIN Room ON Type.TID = Room.TypeID WHERE (((Room.ROID)= " + (roomCB.SelectedIndex + 1).ToString() + "));"
    ad = New OleDb.OleDbDataAdapter(sqlCmd1, cnn)
    ds = New DataSet
    ad.Fill(ds)
    Try
        typeTxt.Text = ds.Tables(0).Rows(0).Item(0)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try


Source: New Questions

1 Comment

  1. Digin Dominic

    Why are you filling a DataTable if you want to retrieve just a single field?
    ExecuteScalar executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

    Also you should use parameterized query in order to avoid SQL Injection.

    Off the top of my head…

    Dim RoomID As String = roomCB.SelectedIndex + 1.ToString()

    Dim sql As String = “SELECT Type.Name FROM Type INNER JOIN Room ON Type.TID = @parameter”

    Using cn As New SqlConnection(“Your Connection string here”), _
    cmd As New SqlCommand(sql, cn)

    cn.Open()
    cmd.Parameters.Add(“@parameter”, SqlDbType.VarChar, 50).Value = RoomID
    typeTxt.Text = cmd.ExecuteScalar().ToString()
    cn.Close()
    End Using

    Reply

Leave a Reply