Apply Formula Cell to a DataGridview

后端 未结 4 1836
独厮守ぢ
独厮守ぢ 2020-12-29 09:49

I want to add formula cell in a DataGridView. Is there any custom DataGridView to do this?

Example:

grid[4, column].Text =         


        
4条回答
  •  别那么骄傲
    2020-12-29 10:16

    A couple of things you could try:

    Handle the cell value changed event to detect when one of the cells used in the calculation changes and calculate the appropriate value. Something like this (try it in a new project)

    Public Class Form1
      Private WithEvents DGV As New DataGridView
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        DGV.SetBounds(20, 50, 400, 200)
        Controls.Add(DGV)
        DGV.Columns.Add("Qty", "Qty")
        DGV.Columns.Add("Price", "Price")
        DGV.Columns.Add("Total", "Total")
        DGV.Columns("Total").ReadOnly = True
        DGV.RowCount = 5
      End Sub
    
      Private Sub DGV_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV.CellValueChanged
        If e.ColumnIndex = DGV.Columns("Qty").Index Or e.ColumnIndex = DGV.Columns("Price").Index Then
          DGV("Total", e.RowIndex).Value = CInt(DGV("Qty", e.RowIndex).Value) * CDbl(DGV("Price", e.RowIndex).Value)
        End If
      End Sub
    End Class
    

    Or rather than reading your file direct to the datagridview read it into a datatable and bind the grid to the datatable. You can then add an expression column in the datatable to do the calculation. Something like this:

    Public Class Form1
      Private WithEvents DGV As New DataGridView
      Private DT As New DataTable
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        DGV.SetBounds(20, 50, 400, 200)
        Controls.Add(DGV)
        DT.Columns.Add("Qty", GetType(Int32))
        DT.Columns.Add("Price", GetType(Double))
        DT.Columns.Add("Total", GetType(Double))
        DT.Columns("Total").Expression = "Qty * Price"
        DGV.DataSource = DT
      End Sub
    End Class
    

提交回复
热议问题