0

I have some code like this

Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'") 

conn.Open() 

Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn) 

dgBookings.DataSource = query.ExecuteReader 
dgBookings.DataBind() 

I need to add in an If statement basically saying if the SQLCommand query returns no rows then show a specific label

Can this be done?

Thanks

2 Answers 2

2

Try:

Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'") 

conn.Open() 

Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn) 

Dim rdr as SqlDataReader
rdr = query.ExecuteReader()

if (rdr.HasRows) then
   dgBookings.DataSource = rdr
   dgBookings.DataBind() 
else
    .....
end if

Obviously you could do with ensuring the objects are cleaned up/disposed of, so this is just to demonstrate HasRows ;)

Sign up to request clarification or add additional context in comments.

2 Comments

This works without the dgBookings.DataSource = query.Executereader when i put that bit in it says There is already an open DataReader associated with this Command which must be closed first
Sorry, copy n paste error! corrected now - should have replaced that to use rdr
2

You are being returned a SqlDataReader when you call ExecuteReader(), and that SqlDataReader has a HasRows property you can check.

Dim oDR As SqlDataReader = query.ExecuteReader()

If oDR.HasRows Then
  lblNoRows.Visible = False
Else
  lblNoRows.Visible = True
End IF

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.