【问题标题】:Cant catch errors when editing编辑时无法捕获错误
【发布时间】:2012-12-30 19:03:26
【问题描述】:

我对 c# 和 winforms 有点陌生,需要一些帮助。

我创建了一个 dataset 并将其插入 2 个表“order_lines”和“products”。我有一个datagridview,其中的列取自表“order_lines”,这是一个空表(没有数据)。

所以在 datagridview 中我有 3 个空列:quantityproduct (这是从另一个数据集表 products 中取出的 combobox 和一列total 我自己创建的(所有其他列,例如 product_idorder_num 都是不可见的)

我正在尝试允许用户编辑 datagridview 中的数据并将其插入到列数量 (插入编号) 到列产品 (从组合框中选择产品) 并且总数应该是quantity*product_price的计算(根据从组合框中选择的产品,每个产品都有一个id,价格应该从products的表中获取,根据产品@987654334 @)

我有两个问题:

  1. 我正在尝试使用cell_validating 事件和data_error 检查用户插入的数据 但它不起作用,当用户输入无效数据时,我没有收到错误消息,而是收到异常 "object cannot be cast from dbnull to other types",我不明白为什么
  2. 我似乎无法从datasetproducts 中获取价格并根据所选产品在总列中使用它(在显示数据集表“order_lines”在数据集表“products”中还有一个隐藏列“product_id”,当用户选择一个产品我需要得到价格。

我希望我设法解释了我的问题,任何想法都将受到高度赞赏

【问题讨论】:

    标签: c# database winforms datagridview dataset


    【解决方案1】:

    我建议你这样做:

    DataTable products;
    
    public Form1()
    {
        InitializeComponent();
    
        // handle cell changes
        dataGridView1.CellValueChanged += dataGridView1_CellValueChanged;
    
        // used for manually raising the ComboBox change
        dataGridView1.CurrentCellDirtyStateChanged += dataGridView1_CurrentCellDirtyStateChanged;
    }
    
    void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        // return if the row or column headers were changed
        if (e.RowIndex < 0 || e.ColumnIndex < 0)
            return;
        if (e.ColumnIndex != dataGridView1.Columns["total"].Index)
        {
            var value = 0;
    
            // get the product id from the ComboBox
            var product = dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Columns["Product"].Index].Value;
    
            // get the quantity
            var quantity = dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Columns["TotalQuantity"].Index].Value.ToString();
    
            if (product != null && !String.IsNullOrEmpty(quantity))
            {
                value =
                    int.Parse(quantity) *
                    int.Parse(products.Select("product_id = " + product.ToString())[0]["product_price"].ToString());
    
                dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Columns["total"].Index].Value = value;
                dataGridView1.Invalidate();
            }
        }
    }
    
    void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2023-01-11
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多