如何在Windows应用程序中的表单加载事件的文本框中显示来自datagridview的计算量

时间:2014-04-23 17:42:08

标签: c# winforms datagridview

我正在使用一个文本框和datagridview。其中我使用gridview单元格进行了计算(总金额),整个单元格的总量显示在文本框中。但它仅在编辑模式下显示。我想要总值也显示在表格加载时间。

private void datagrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
     double value1 = datagrid.Rows[e.RowIndex].Cells[2].Value == DBNull.Value ? 0 : Convert.ToDouble(datagrid.Rows[e.RowIndex].Cells[2].Value);
     double value2 = datagrid.Rows[e.RowIndex].Cells[3].Value == DBNull.Value ? 0 : Convert.ToDouble(datagrid.Rows[e.RowIndex].Cells[3].Value);
     double value3 = datagrid.Rows[e.RowIndex].Cells[4].Value == DBNull.Value ? 0 : Convert.ToDouble(datagrid.Rows[e.RowIndex].Cells[4].Value);
     double value4 = datagrid.Rows[e.RowIndex].Cells[5].Value == DBNull.Value ? 0 : Convert.ToDouble(datagrid.Rows[e.RowIndex].Cells[5].Value);
     datagrid.Rows[e.RowIndex].Cells[6].Value = ((value2 + (value3/100)) * value1) - (value4/100);

     if (e.ColumnIndex == 5)
     {
        summition();
     }
}
void summition()
{
     double sum = 0;
     foreach (DataGridViewRow row in datagrid.Rows)
     {
         if (!row.IsNewRow)
             sum += Convert.ToDouble(row.Cells[6].Value.ToString());
     }    
     texttotal.Text = sum.ToString();
}

here is my form_load eveny code:

 private void Purchase_Load(object sender, EventArgs e)
        {
bindgrid();
}

        private void bindgrid()
        {
 try
                       {

                 con.Open();
                SqlCommand cmd = new SqlCommand("select distinct product_id,product_name,qty,price,tax,discount,total  from Purchasedetail", con);
                da.SelectCommand = cmd;
                cmd.ExecuteNonQuery();
                DataSet ds = new DataSet();
                da.Fill(ds, "Purchsedetail");
                datagrid.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught : " + ex.Message.ToString());
            }
            finally
            {
                con.Close();
            }
        }

0 个答案:

没有答案