首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

指定的转换无效。该如何处理

2012-05-28 
指定的转换无效。C# codepublic ListPetShop.Model.ItemInfo GetItemById(string ItemId){string sql

指定的转换无效。

C# code
public List<PetShop.Model.ItemInfo> GetItemById(string ItemId)               {            string sql = "select item.itemid, item.name, item.listprice, product.name, item.image, product.categoryid, product.productid from item inner join product on item.productid = product.productid where item.itemid = @itemid";            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ssa"].ConnectionString;                   List<PetShop.Model.ItemInfo> list = new List<PetShop.Model.ItemInfo>();            using (SqlConnection connection = new SqlConnection(connectionString))            {                SqlCommand command = new SqlCommand(sql, connection);                connection.Open();                command.Parameters.Add("@itemid", SqlDbType.NVarChar).Value = ItemId;                SqlDataReader reader = command.ExecuteReader();                if (reader.Read())                {                     PetShop.Model.ItemInfo item = new PetShop.Model.ItemInfo()                    {                        ItemId = reader.GetString(0),                        Name = reader.GetString(1),                        Quantity = reader.GetInt32(2),                        ListPrice = reader.GetDecimal(3),                        ProductName = reader.GetString(4),                        Image = reader.GetString(5),                        CategoryId = reader.GetString(6),                        ProductId = reader.GetString(7)                    };                                list.Add(item);                }                return list;                           }


[解决办法]
赋值之前最好判断一下值是否为空
ItemId = reader.GetString(0),
如果为空,转换为string 肯定报错

热点排行