Monday, 27 July 2015

How to find text change in data grid view and calculate in data grid view in vb.net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim table As New DataTable

        With table.Columns
            .Add("Column1", GetType(Integer))
            .Add("Column2", GetType(Integer))
            .Add("Sum", GetType(Integer))
        End With
        Me.DataGridView1.DataSource = table
    End Sub
    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        AddHandler e.Control.TextChanged, AddressOf CellTextChanged
    End Sub

    Private Sub CellTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim txt As DataGridViewTextBoxEditingControl
        Dim col1 As Integer
        Dim col2 As Integer

        Try
            If DataGridView1.CurrentCell.ColumnIndex = 0 Then
                txt = DirectCast(sender, DataGridViewTextBoxEditingControl)
                If txt.Text.Length > 0 Then
                    col1 = Integer.Parse(txt.Text)
                End If
                If DataGridView1.CurrentRow.Cells("Column2").Value & "" <> "" Then
                    col2 = Integer.Parse(DataGridView1.CurrentRow.Cells("Column2").Value)
                End If
            ElseIf DataGridView1.CurrentCell.ColumnIndex = 1 Then
                txt = DirectCast(sender, DataGridViewTextBoxEditingControl)
                If DataGridView1.CurrentRow.Cells("Column1").Value & "" <> "" Then
                    col1 = Integer.Parse(DataGridView1.CurrentRow.Cells("Column1").Value)
                End If
                If txt.Text.Length > 0 Then
                    col2 = Integer.Parse(txt.Text)
                End If
            End If
            DataGridView1.CurrentRow.Cells("sum").Value = col1 + col2
        Catch ex As Exception
            MessageBox.Show("Input string was not in a correct format.")
        End Try
    End Sub

No comments:

Post a Comment