I've been trying to get data from a local database in asp.net web service .asmx page but I only get one element back, and not even the first element. When i try another index, i get index out of bounds of array exception, but i know it's not because my database is larger than whatever index i try.
Here is my current .asmx code
<%@ WebService Language="C#" Class="PostWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class PostWebService : System.Web.Services.WebService {
int result;
[WebMethod]
public int GetRates() {
//try
//{
SqlConnection connection = new SqlConnection(@"Data Source = (local); Initial Catalog = RatesDB; Integrated Security=True");
SqlCommand cmd = new SqlCommand(" select HeartRate from Rates order by HeartRate DESC", connection);
connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
int i = 0;
while (dr.Read())
{
result = Convert.ToInt32(dr[i++]);
Console.WriteLine(result);
}
dr.Close();
connection.Close();
//}
//finally
//{
//}
return result;
}
}
I've been playing with the code to try to get a different result but i keep getting error:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, Boolean allowPartiallyReadColumn, Boolean permitAsync, String methodName)
at System.Data.SqlClient.SqlDataReader.TryReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn)
at System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32 i)
at System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
at System.Data.SqlClient.SqlDataReader.get_Item(Int32 i)
at PostWebService.GetRates() in C:\Users\Rommel\Desktop\Website\Website\Website\PostWebService.asmx:line 28
If i use 0 as my index for dr[0] then i can read a value but it's not even the first one, so i do not understand why it is reading my database incorrectly. Any tips in the right direction or even corrections in my code would be appreciated.