2012-06-14 131 views
3

我有一个DataGridView,其中有一列'总'。 DataGridView是可编辑的true。在网格视图下方我有文本框,其中我想要网格的“总计”列的总数。我所做的是,当用户输入到网格中的总列中时,它会反映到网格视图中的总文本字段中。要在文本框中显示总数,我添加了网格视图的总列。但问题是,如果我第一次进入网格视图的总列,它会立即反映到下面的文本字段中。但如果我在DataGridView的总列中编辑相同的值,则网格下方的文本字段会将其与之前的值相加,以便在文本字段中显示新编辑的值。如何解决这个问题以下是代码: -DataGridView单元格编辑结束事件

private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    try 
    { 
     string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); 
     if (e.ColumnIndex == 1) 
     { 
      // int val = int.Parse(value); 
      // quantity = val; 
      // ekundag = ekundag + quantity; 
      //tbTotDag_cr.Text =ekundag.ToString(); 

      int quantity = 0; 

      foreach (DataGridViewRow row in grdCaret.Rows) 
       quantity +=(int) grdCaret.Rows[e.RowIndex].Cells[1].Value.ToString(); 
       //quantity +=(int) row.Cells[1].Value; 

      tbTotDag_cr.Text = quantity.ToString(); 
     } 

     if (e.ColumnIndex == 2) 
     { 
      float val = float.Parse(value); 
      total = val; 
      ekunrakam = ekunrakam + total; 
      tbTotPrice_cr.Text = ekunrakam.ToString(); 
     } 
     grdCaret.Columns[3].ReadOnly = false; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message.ToString()); 
    } 
} 
+0

你能在这里提供你的编辑事件处理程序代码? –

+0

你如何运行汇总,代码请 – V4Vendetta

回答

4

使用CellEndEdit事件来更新您的总价值:

private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    int total = 0; 

    foreach (DataGridViewRow row in dataGridView.Rows)    
     total += (int)row.Cells[columnTotal.Index].Value; 

    totalTextBox.Text = total.ToString();   
} 
+0

我做了同样的..但问题是,每当我编辑网格中的同一列,文本框中的前一个值添加新的编辑值。我想只有新的值不是在文本框中的以前的值。 – Harshali

+0

也许你正在使用当前文本框的值初始化total,而不是零。 –

0
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
{ 
    if (dataGridView.Rows.Count > 0) 
    { 
    Double dobTotal = 0.00; 
    if (dataGridView.Columns["colAmountPaid"].Name.ToString().Equals("colAmountPaid")) 
     { 
     for (int i = 0; i < dataGridView.Rows.Count; i++) 
     { 
     dobTotal += Double.Parse(dataGridView["colAmountPaid",i].EditedFormattedValue.ToString()); 
     } 
     txtTotal.Text = dobTotal.ToString(); 
     } 
    } 
    } 
+0

你能解释你的代码吗? –

0
<code>Private Sub EndEdit(ByVal sender As System.Object, ByVal e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged 
     If DataGridView1.IsCurrentCellDirty Then 
      DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit) 
     End If 
    End Sub 

<code> 
    Private Sub DataGridView1_TextChanged(ByVal sender As System.Object, ByVal e As 
    System.Windows.Forms.DataGridViewCellEventArgs) Handles 
           DataGridView1.CellValueChanged 
     If e.RowIndex = -1 Then 
      isdirty = True 
     End If 

//All code you want to perform on change event 

<code> End Sub 
</code> 
相关问题