1 public List<Member> GetAllMembers()
2 {
3 SqlConnection con = new SqlConnection(conStr);
4 SqlCommand com = new SqlCommand("GetAllMember", con);
5 com.CommandType = CommandType.StoredProcedure;
6 List<Member> Members = new List<Member>();
7 try
8 {
9 con.Open();
10 SqlDataReader red = com.ExecuteReader();
11 while(red.Read())
12 {
13 Member mem = new Member((int)red["ID"],Convert.ToString(red["MName"]),
14 Convert.ToString(red["pwd"]), Convert.ToString(red["cls"]),
15 (int)red["age"]);
16 Members.Add(mem);
17 }
18 red.Close();
19 return Members;
20 }
21 catch (SqlException err)
22 {
23 throw new ApplicationException("GetAllMembers错误");
24 }
25 finally
26 {
27 con.Close();
28 }
29 }
运行时提示在Member mem = new Member((int)red["ID"],Convert.ToString(red["MName"]), Convert.ToString(red["pwd"]), Convert.ToString(red["cls"]), (int)red["age"]);这句出现System.InvalidCastException: 指定的转换无效
注:1 此方法是在objectDataSource的SelectMethod调用的。
2 存储过程也没有问题
数据库中的 tinyint的类型 对应与C#中的是byte 类型。
你应该是(byte)red["age"]
或者用强制转换:Convert.ToInt32(red["age"])
What does it normally come back as - byte? If so, just do an unbox and then a convert:
(int)(byte) reader["column"];
or just let the conversion happen naturally:
int x = (byte) reader["column"];
or do the same with the strongly typed methods:
int x = reader.GetByte(column);
来源:http://stackoverflow.com/questions/1922094/how-can-you-convert-tinyint-of-t-sql-to-integer-in-c