Noni
Noni

Reputation: 369

web service page System.IndexOutOfRangeException

public class GetAreaFromCity : System.Web.Services.WebService
{
    [WebMethod]
    public GetAreaByCityId ClassForGetCIty(int City_Id)
    {
        string CS =ConfigurationManager.ConnectionStrings["FOODINNConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("spGetCityById",con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter parameter = new SqlParameter("@ID", City_Id);

            //To assiate this parameter object with cmd object
            cmd.Parameters.Add(parameter);
            GetAreaByCityId GETAreaByCityId =new GetAreaByCityId();
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            //as WeakReference read data wewant ToString retrive Column value & then polute this property City_Id values
            while (reader.Read()){
                GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
                GETAreaByCityId.Area_Id =     Convert.ToInt32(reader["Area_Id"]);

            }
            return GETAreaByCityId;

            //ToString return sql
        }
    }
}

that's my codes for service page

public class GetAreaByCityId
{
    public int Ca_Id {get;set; }
    public int City_Id { get; set; }
    public int Area_Id { get; set; }
}

that's the class for getting the Area by city

Create Proc [dbo].[spGetCityById]
@ID int 
as
Begin
Select Area_Id from 
CITIES_AREA where City_Id = @ID
End
GO

and above the database procedure which is data can be retrieve

System.IndexOutOfRangeException: City_Id at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName) at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name) at System.Data.SqlClient.SqlDataReader.get_Item(String name) at WebApplication1.GetAreaFromCity.ClassForGetCIty(Int32 City_Id) in c:\Users\Mudassir\Documents\Visual Studio 2013\Projects\WebApplication1\WebAppli

the above error i dont know whats the problem

Upvotes: 0

Views: 484

Answers (1)

David Tansey
David Tansey

Reputation: 6023

Your stored procedure is returning only Area_Id. Your code in the "while loop" while (reader.Read()){ is attempting to read data from two columns:

  • City_Id
  • Area_Id

You could add the column City_Id to the result set for your stored procedure query, BUT you already have that value because you are passing it to the stored procedure as a parameter.

Easiest fix is probably to just change this line:

GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);

to this:

GETAreaByCityId.City_Id = City_Id;

Upvotes: 2

Related Questions