How to set value of a DataGridView Cell programatically?

末鹿安然 提交于 2020-01-25 11:36:05

问题


I am trying to clear the cell if certain conditions are met. But its not working.

UPDATE

 Private Sub DataGridView1_CellLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellLeave
        Dim laspac As Int16 = DataGridView1.Columns("LASPAC").Index

        If e.ColumnIndex = laspac And DataGridView1.Rows(e.RowIndex).Cells("CType").Value.ToString.Trim() = "B" Then
            Dim B_LASPAC As DataGridViewCell = DataGridView1.Rows(e.RowIndex).Cells("LASPAC")
            Dim A_LASPAC As DataGridViewCell = DataGridView1.Rows(e.RowIndex - 1).Cells("LASPAC")
            If B_LASPAC.Value.ToString.Trim.Length <> 0 Then

                If Convert.ToDecimal(B_LASPAC.Value) + Convert.ToDecimal(A_LASPAC.Value) > 0 Then

                    B_LASPAC.Value = ""


                End If
            End If


        End If
    End Sub

回答1:


It's very easy, just pass the RowIndex and ColumnIndex

eg.

Dim rowId = 0
Dim colId = 1

DataGridView1(colId, rowId).Value = "HELLO"

so, in your case... something like

If ... Then
    DataGridView1(e.ColumnIndex, e.RowIndex).Value = ""
End If



回答2:


I had to use B_LASPAC.EditedFormattedValue.ToString() instead of B_LASPAC.Value.ToString() to get the value of the cell on cell leave and also I realized that I need to end the EditMode of the DataGridView by using DataGridView1.EndEdit() just before I set the new value of the cell B_LASPAC.Value = ""

 Private Sub DataGridView1_CellLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellLeave
        Dim laspac As Int16 = DataGridView1.Columns("LASPAC").Index

        If e.ColumnIndex = laspac And DataGridView1.Rows(e.RowIndex).Cells("CType").Value.ToString.Trim() = "B" Then
            Dim B_LASPAC As DataGridViewCell = DataGridView1.Rows(e.RowIndex).Cells("LASPAC")
            Dim A_LASPAC As DataGridViewCell = DataGridView1.Rows(e.RowIndex - 1).Cells("LASPAC")
            Dim str As String = DataGridView1.Rows(e.RowIndex).Cells("LASPAC").EditedFormattedValue.ToString()
            If B_LASPAC.EditedFormattedValue.ToString.Trim.Length <> 0 Then
                If Convert.ToDecimal(B_LASPAC.EditedFormattedValue.ToString()) + Convert.ToDecimal(A_LASPAC.EditedFormattedValue.ToString()) > 0 Then

                    DataGridView1.EndEdit()
                    B_LASPAC.Value = ""

                End If
            End If
        End If
    End Sub


来源:https://stackoverflow.com/questions/20969453/how-to-set-value-of-a-datagridview-cell-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!