编辑时无法捕获错误

时间:2013-01-16 12:44:33

标签: c# database winforms datagridview dataset

我是c#的新手,并且需要一些帮助。

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

所以在datagridview我有3个空列:quantityproduct (这是combobox取自其他数据集表{{1我自己创建的products (所有其他列,例如totalproduct_id都是不可见的)。< / p>

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

我有两个问题:

  1. 我正在尝试使用id事件和cell_validating检查用户插入的数据 但它不起作用,而不是在用户输入无效数据时收到我的错误消息我得到异常data_error,我不明白为什么
  2. 我似乎无法从"object cannot be cast from dbnull to other types"dataset中获取价格,并根据所选产品在总列中使用它(在datagridview中显示数据集表“< strong> order_lines “还有一个隐藏列”product_id“也在数据集表”产品“中我有”product_id“列和”product_name“,这是datagridview中的组合框)用户选择我需要的产品。
  3. 我希望我设法解释我的问题,任何想法都将受到高度赞赏

1 个答案:

答案 0 :(得分:0)

我建议你这样做:

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);
}