Click here to Skip to main content
15,850,685 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I fill the datagrid per code.
Setting the Format "N2" in Code or in Designer doesn´t make any difference.
The problem seems to be that I have NULL in this column too.
I want no display when NULL and and a 2-digit value when not NULL.
Is this possible?

Attempts with CDdec, Math.round don´t fit, because of error with NULL.

What I have tried:

dgvProduktion.Rows.Add(..., dreader("AZmin").ToString() ,...)

CDec and Math.round don´t work with NULL
Updated 16-Jun-23 2:44am

Wrap the data in a method that handles the formatting.

For example, change:

Function FormatData(value As Double?) As String

    If value Is Nothing Then
        Return ""
    End If

    Return value.ToString()

End Function

Where value_type is the filed value type, eg: double, float, decimal, etc...

Then to use:
dgvProduktion.Rows.Add(..., FormatData(dreader("AZmin")) ,...)
Share this answer
Add a null conditional operator: Member access and null-conditional operators and expressions: | Microsoft Learn[^]
dgvProduktion.Rows.Add(..., dreader("AZmin")?.ToString() ,...)
Share this answer
Graeme_Grant 16-Jun-23 6:29am    
Not supported in VB (I think), you will get the following compile error:
BC30487	Operator '?' is not defined for type 'Double'
OriginalGriff 16-Jun-23 6:51am    
You sure?

I just checked and it works for me:
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str As String = Nothing
        If str?.ToString() Is Nothing Then
        End If
    End Sub
Graeme_Grant 16-Jun-23 6:58am    
Hmm... .Net Core or .Net Framework. I used .Net Framework as many avoid .Net Core. Also, check my answer below.

His question indicates the value is numeric, not a string, hence the cast ToString. Try this test:
Dim value As Double = Nothing
OriginalGriff 16-Jun-23 7:15am    
If it's a Double, it can't contain a null value anyway - it's a value type, not reference.
It would have to be a Double? but that would mean he wouldn't get the problem anyway ... (I think, I've not played with nullable types in VB)
Graeme_Grant 16-Jun-23 7:16am    
Nullable types have very limited support in VB. We are spoilt in C#, especially in .Net Core.
So it works:

Function FormatN2(value As String) As String
    If value = "" Then
        Return ""
        value = Math.Round(CDec(value), 2)
    End If

    Return value.ToString()
End Function
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900