Reputation: 15
I am working on Web Page is visual studio using C#, and I am pulling the columns below into a collection of new authors.
I keep getting a Specified Cast Is Not Valid error
. I think it has to do with my int "au_id."My professor has given us a database where the id is an nvarchar, not an int, so I need to convert it so that it is. Below is the code:
colauthors.Add(new authors(
(int)reader["au_id"],
(string)reader["au_lname"],
(string)reader["au_fname"],
(string)reader["phone"],
(string)reader["address"],
(string)reader["city"],
(string)reader["state"],
(string)reader["zip"],
(bool)reader["contract"]));
And this is how the columns are in the database along with their data types:
au_id nvarchar(50)
au_lname nvarchar (50)
au_fname nvarchar (50)
phone char (12)
address nvarchar (50)
city nvarchar (50)
state char (2)
zip char (5)
contract bit
I know that for contract the bit will be a bool, and I'm pretty sure that char's are strings. So I am almost positive my error has to do with the id, I just can't figure out how to cast it correctly. Any suggestions?
Upvotes: 1
Views: 3389
Reputation: 148980
You must change the datatype of the au_id
column to an integer (or related datatype), or parse the value as a string in c# as Attila Kurucz suggests.
There could also be problems if the contract
or au_id
column is null
. Try this
(int)!reader.IsDbNull(reader.GetOrdinal("au_id")) && reader["au_id"]
...
(bool)!reader.IsDbNull(reader.GetOrdinal("contract")) && reader["contract"]
or this (although it will require you to tweak your authors
class slightly).
(int?)reader["au_id"]
...
(bool?)reader["contract"]
To specify a default value in the event that a column is null
try this.
((int?)reader["au_id"]) ?? 0
...
((bool?)reader["contract"]) ?? false
Upvotes: 1
Reputation: 160
If the au_id type is nvarchar in the db then it will fail for both of the enumerated conversions (ex. "abc" can't be converted to int). You could try int.tryparse wich in case of failure returns false allowing you to provide some alternate id.
Upvotes: 2