-1

I need get data from sqlite database, but I get this error:

System.InvalidCastException: 'Specified cast is not valid.'

Am I changing type of data in a bad way?

conn.Open();
string stm = new CustomQueries().GetUsersByName(this.searchedName, this.searchedSurname);

SQLiteCommand cmd = new SQLiteCommand(stm, conn);
SQLiteDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    this.personResults.Add(new Person(
                    (int)rdr["Id"],
                    (int)rdr["School_id"],
                    (int)rdr["Role_id"],
                    (string)rdr["Name"],
                    (string)rdr["Surname"],
                    (int)rdr["Study_year"],
                    (string)rdr["Identification_number"],
                    (string)rdr["Address"],
                    (string)rdr["Phone"],
                    (string)rdr["Email"],
                    (int)rdr["Age"],
                    (string)rdr["Birth_date"],
                    (string)rdr["Year_letter"]
                    ));
}

conn.Close();

My database structure is same as fields in code. Columns are of type Text or int in the database - again same as type in ()

edit> Query:

 public string GetUsersByName(string name, string surname)
        {
            return "select * from user where name LIKE '%" + name + "%' and surname LIKE '%" + surname + "%'";
        }

DB User table structure

enter image description here

Young L.
  • 922
  • 3
  • 13
  • 33

1 Answers1

0

you are trying to convert a value or an object to its string representation by using a casting operator . When you execute the program you will get " System.InvalidCastException : Unable to cast object of type 'System.Int32' to type 'System.String'."

The ToString() method is defined by the Object class and therefore is either inherited or overridden by all managed types. So, here we call its ToString method because it successfully covert an instance of any type to its string representation .

(int)rdr["Id"] Here is the problem. you can use Convert.ToInt32(rdr["Id"]) to fix your problem.

MD. RAKIB HASAN
  • 3,670
  • 4
  • 22
  • 35
  • Yes thsi fix the problem thx – Young L. Jan 17 '21 at 11:05
  • @YoungL. This would _not_ fix the issues for int - but it will (kind of) for strings that are `NULL` in the database (although @Rakib's explanation of _why_ is wrong). – mjwills Jan 17 '21 at 11:08