I want to return an array of Strings in the form \"abc#xyz#ghi#tru\" (where # is delimiter) from my web service method . However i m not able to do it . Here is my current web s
Try this:
I changed the query (BTW: the query still doesn't make much sense but I do not know what you really want), the resulting type and the loop.
You forgot to pass the parameter to the query too.
Also: change the exception handling; writing to the console on the server side is not a good idea.
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String getData(string nameFilter)
{
String result = "";
SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
try
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "select name from names where name =@name";
myCommand.Parameters.AddWithValue("@name", nameFilter);
SqlDataReader myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
if(result.Length > 0)
{
result += "#";
}
result += myReader["name"].ToString();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
myConnection.Close();
}
return result;
}
}
EDIT
I'd prefer a different approach:
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String[] getData(string nameFilter)
{
var names = new List();
SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
try
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "select name from names where name = @name";
myCommand.Parameters.AddWithValue("@name", nameFilter);
SqlDataReader myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
names.Add(myReader["name"].ToString());
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
finally
{
myConnection.Close();
}
return names.ToArray();
}
}