Reputation: 5186
[WebMethod]
public List< string> HelloWorld(string prefixText)
{
SqlConnection con = new SqlConnection("Database=bluedd;Server=(local);Integrated Security=SSPI");
con.Open();
SqlCommand cmd = new SqlCommand("select user_master.first_name from user_master where first_name like @Name+'%'", con);
cmd.Parameters.AddWithValue("@Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> CountryNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CountryNames.Add(dt.Rows[i].ToString());
}
return CountryNames;
}
This code returns System.Data.DataRow is there any casting problem
I am very new in s/w Development, any help will be appreciated
Upvotes: 1
Views: 702
Reputation: 415665
You need to tell it which column in the row. "System.Data.DataRow
" is the result of calling .ToString() on the row object itself. Try this:
[WebMethod]
public List<string> HelloWorld(string prefixText)
{
var result = new List<string>();
using (var con = new SqlConnection("Database=bluedd;Server=(local);Integrated Security=SSPI"))
{
using (var cmd = new SqlCommand("select user_master.first_name from user_master where first_name like @Name+'%'", con))
{
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = prefixText;
con.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
result.Add(rdr[0].ToString());
}
}
}
}
return result;
}
Note that I made several other changes as well. You probably won't understand all of them yet, but I had a reason for every one of them. The most important change, and what you should start doing right now, is the using
blocks. These make sure the certain objects are disposed of (closed) correctly.
Upvotes: 1
Reputation: 588
Your code is returning the data row. To return the column you would do something like
CountryNames.Add(dt.Rows[i][0]);
I think what you want is to replace your for loop with this.
foreach(DataRow row in dt.Rows)
{
CountryNames.Add(row[0]);
}
return CountryNames;
Upvotes: 1