Reputation: 3527
I keep getting this error when I try to build my solution. I've tried public string
and just public
but can't get it to work. Any ideas? Thanks!
[WebMethod]
public static LoadCitiesByState(string state)
{
DataTable dt = SharedDataAccess.GetCities(state);
List<string> cities = new List<string>();
foreach (DataRow row in dt.Rows)
{
cities.Add(row[0].ToString());
}
return cities;
}
EDIT
Now I get the error: "Not all code paths return a value"
EDIT II
Sorry forgot to paste the try & catch I had in there. I removed them and it worked. If anyone wants to show how to get it to work with a try & catch, feel free though.
Upvotes: 0
Views: 3917
Reputation: 47770
You need to specify the type of the variable you're returning:
public static List<string> LoadCitiesByState(string state)
You need to make sure that something gets returned regardless of whether there is an exception thrown or not. So declare the return variable beforehand, and return it after the try/catch block:
public static List<string> LoadCitiesByState(string state)
{
List<string> cities = new List<string>();
try {
DataTable dt = SharedDataAccess.GetCities(state);
} catch // specify exceptions here
{
//exception handling
}
foreach (DataRow row in dt.Rows)
{
cities.Add(row[0].ToString());
}
return cities;
}
In general it's always a good idea to minimize the number of lines you have inside the try block.
Upvotes: 13
Reputation: 18237
the problem with your method it's that you need to define which type of data are you going to return
[WebMethod]
public static List<string> LoadCitiesByState(string state)
{
DataTable dt = SharedDataAccess.GetCities(state);
List<string> cities = new List<string>();
foreach (DataRow row in dt.Rows)
{
cities.Add(row[0].ToString());
}
return cities;
}
And that's all
UPDATE
If you want to add the try and catch you could do it like this
[WebMethod]
public static List<string> LoadCitiesByState(string state)
{
List<string> cities = new List<string>();
try
{
DataTable dt = SharedDataAccess.GetCities(state);
foreach (DataRow row in dt.Rows)
{
cities.Add(row[0].ToString());
}
}
catch(Exception e)
{
//logs your exception
}
return cities;
}
Upvotes: 4
Reputation: 129
You need to specify return type, try this
[WebMethod]
public static List<string> LoadCitiesByState(string state)
{
DataTable dt = SharedDataAccess.GetCities(state);
List<string> cities = new List<string>();
foreach (DataRow row in dt.Rows)
{
cities.Add(row[0].ToString());
}
return cities;
}
Upvotes: 1
Reputation: 31394
You are returning cities with is a List<string>
so that should be your return type.
public static List<string> LoadCitiesByState(string state)
Upvotes: 6