You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

System.InvalidCastException异常:usprouduct无法转换为IConvertible

问题描述

开发了一个用于展示产品的User Control,多数功能运行正常,但在打印发票的清单窗体中,首次添加产品无问题,重复添加同一产品时触发以下异常:

System.InvalidCastException:Unable to cast object of type fast_food.Modele.usproduct to type System.IConvertible

已检查User Control及转换相关代码,但未定位到问题所在。以下是相关代码片段:

转换方法代码

private void AddItems(string id,string proID ,string name, string cat, string price, Image pimage)
 {
     var w = new usprouduct()
     {
         pName = name,
         pPrice = price,
         pCategory = cat,
         pImage = pimage,
         id = Convert.ToInt32(proID)
     };
     prouductpanel.Controls.Add(w);

     w.oneSelect += (ss, ee) =>
     {
         var wdg = (usprouduct)ss;

         foreach (DataGridViewRow item in guna2DataGridView1.Rows)
         {
             if (Convert.ToInt32(item.Cells["dgvproid"].Value) == wdg.id)
             {
                 item.Cells["dgvQty"].Value = int.Parse(item.Cells["dgvQty"].Value.ToString()) + 1;
                 item.Cells["dgvAmount"].Value = int.Parse(item.Cells["dgvQty"].Value.ToString()) *
                  double.Parse(item.Cells["dgvprice"].Value.ToString());
                 return;
             }
             
         }
         // افزودن یک محصول
         guna2DataGridView1.Rows.Add(new object[] {0, 0, wdg, id, wdg.pName, 1, wdg.pPrice, wdg.pPrice });
         GetTotal();
     };
 }

User Control代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace fast_food.Modele
{
    
    public partial class usprouduct : UserControl
    {
        public usprouduct()
        {
            InitializeComponent();
        }
        public event EventHandler oneSelect = null;
        public int id { get; set; }
        public string pPrice { get; set; }
        public string pCategory { get; set; }

        public string pName
        {
            get { return labelName.Text; }
            set { labelName.Text = value; }

        }

        public Image pImage
        {
            get { return image1.Image; }
            set { image1.Image = value; }

        }

        private void image1_Click(object sender, EventArgs e)
        {
           oneSelect?.Invoke(this,e);
        }
    }
}

GetTotal方法代码

private void GetTotal()
 {
     double total = 0;
     labeltotal.Text = "";

     foreach(DataGridViewRow item in guna2DataGridView1.Rows)
     {
         total += double.Parse(item.Cells["dgvAmount"].Value.ToString());

     }
     labeltotal.Text = total.ToString("N2");
 }
问题原因及解决办法

原因分析

异常触发在Convert.ToInt32(item.Cells["dgvproid"].Value)这一行。查看添加行的代码:

guna2DataGridView1.Rows.Add(new object[] {0, 0, wdg, id, wdg.pName, 1, wdg.pPrice, wdg.pPrice });

第三个参数直接传入了wdg(即usprouduct控件实例),而循环时将该位置的取值当作dgvproid列的内容,尝试把控件实例强制转换为IConvertible类型以转为int,必然抛出类型转换异常。

解决办法

  1. 修正行参数的对应关系:检查DataGridView的列顺序,将产品ID(wdg.id)放到dgvproid列对应的索引位置。例如假设第二列是dgvproid,修改添加行代码为:
guna2DataGridView1.Rows.Add(new object[] {0, wdg.id, wdg, id, wdg.pName, 1, wdg.pPrice, wdg.pPrice });

(需根据实际列顺序调整wdg.id的位置)

  1. 优化类型转换的安全性:避免直接对单元格值做强制转换,先校验值的有效性:
foreach (DataGridViewRow item in guna2DataGridView1.Rows)
{
    if (item.Cells["dgvproid"].Value != null && int.TryParse(item.Cells["dgvproid"].Value.ToString(), out int proId))
    {
        if (proId == wdg.id)
        {
            item.Cells["dgvQty"].Value = int.Parse(item.Cells["dgvQty"].Value.ToString()) + 1;
            item.Cells["dgvAmount"].Value = int.Parse(item.Cells["dgvQty"].Value.ToString()) *
             double.Parse(item.Cells["dgvprice"].Value.ToString());
            return;
        }
    }
}

内容的提问来源于stack exchange,提问作者abbas akhondi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:16:01