Error Unable to overlay object of type "System.Int32" on type "System.String"

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)
0
source share
3 answers

Try result.Add(dr.GetValue(0).ToString());

To avoid GetValue () returning null do this -

result.Add((sqlreader.IsDBNull(0) ? "" : dr.GetValue(0).ToString());
+2
source

when i select an int column

According to the code, you are trying to select a column of type string:

dr.GetString(0)

If the column is equal int, then get int:

dr.GetInt32(0)

What you can convert to stringfor your list:

result.Add(dr.GetInt32(0).ToString());

, :

; .

+8

: 'System.Int32', 'System.String'

, ,

dr.GetString(1)

int,

dr.GetInt32(0)

: .

, ,

dr.GetString(1)

dr.GetString(0), , . , int, , dr.GetInt32(0) not dr.GetInt32(1)

0

Source: https://habr.com/ru/post/1761356/


All Articles