Oak_3260548
Oak_3260548

Reputation: 2000

VB.net DataGridView change Cell.FormattedValue

how do I change the string/value (cell.FormattedValue), which appears in EditMode after user double clicks a cell?

I.e. the value is "5", formated value is "5 pcs" and this is causing error on validation. So I wan't to replace the string which appears to user from "5 pcs" back to "5". Then it should work the same way like when user simpy starts to write "5" and presses Enter.

This is not possible, FormattedValue is ReadOnly:

Me.dgwNest1.Rows(e.RowIndex).Cells(e.ColumnIndex).FormattedValue = 5

Cell.Value is not usable, as it only changes the value portion of edited string.

Regards,

Libor

Upvotes: 3

Views: 3328

Answers (1)

Hawkeye
Hawkeye

Reputation: 638

Just call the FormattedValueType property which raises the DataGridView.CellFormatting event and then change the cell style in the event code.

The FormattedValue is only a formatted representation of the Value property. The FormattedValue representation is specified by the FormattedValueType property.

If you change the FormattedValueType property it will change the way it is presented to the user without changing the value. =)

These remarks from the MSDN show you how to edit the FormattedValue:

The Value property is the actual data object contained by the cell, whereas the FormattedValue is the formatted representation of this object. The ValueType and FormattedValueType properties correspond to the data types of these values, respectively.

Getting the value of this property calls the GetFormattedValue method to convert the cell value into an equivalent display value of the type indicated by the FormattedValueType property. This raises the DataGridView.CellFormatting event, which you can handle to customize the value conversion.

See the remarks on MSDN for the DataGridViewCell.FormattedValue Property here.

When the CellFormatting event is raised you could do something like this:

Private Sub dgvMyData_CellFormatting(sender As System.Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvMyData.CellFormatting
    Dim MyStyle As New System.Windows.Forms.DataGridViewCellStyle

    MyStyle.Format = "00 ct"
    'or to remove the formatting:
    MyStyle.Format = "00"

    e.CellStyle = MyStyle
End Sub

Upvotes: 1

Related Questions