I use the function below to get values from a database.
The problem is that I select an int column.
I get this error Unable to cast object of type 'System.Int32' to type 'System.String'.
in this line result.Add(dr.GetString(0));
the code
[WebMethod]
public static List<string> GetAutoCompleteData(string value, string filterBy)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
con.Open();
string command = string.Format("select {0} from Users where {0} LIKE '%'+@SearchText+'%'", filterBy);
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("@SearchText", value);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<string> result = new List<string>();
while (dr.Read())
{
result.Add(dr.GetString(0));
}
return result;
}
}
}
}
User table structure
UserID type int
UserName type nvarchar(50)
Password type nvarchar(50)
Ayman source
share