Home > Blockchain >  Specifying Value Range for Grid Value VB.NET
Specifying Value Range for Grid Value VB.NET

Time:12-04

How can I avoid getting this warning ? If warning and code stays as below, will the software throw run time error ? Which is better way to write this code ? Since I cannot use Minimum and Maximum for Grid value, I have to use only .Value due to which I have written following code.

Select Case CSng(dgv_config.Item(dgv_config.Columns("p").Index, rowindex).Value)
                        
Case 1 To 150

#Disable Warning BC42019 ' Operands of type Object used for operator
                            If dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value > 400 Then
#Enable Warning BC42019 ' Operands of type Object used for operator
                                dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value = 400
                            End If
#Disable Warning BC42019 ' Operands of type Object used for operator
                            If dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value < 50 Then
#Enable Warning BC42019 ' Operands of type Object used for operator
                                dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value = 50
                            End If
End Select

CodePudding user response:

Hursey's comment is correct, a type casting would remove the warnings.

To explain I will rewrite some of your code to make it clearer, from this...

If dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value > 400 Then
    dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value = 400
End If

...to this:

Dim columnIndex As Integer = dgv_config.Columns("tsamp").Index
Dim cellValue As Object = dgv_config.Item(columnIndex, rowindex).Value

If cellValue > 400 Then
    dgv_config.Item(columnIndex, rowindex).Value = 400
End If

Notice how cellValue is of type Object. That is because the DataGridViewCell.Value property returns an object. The reason for this is because there can be different types of content in the cell, such as a string or an integer. Your column will contain an integer, but the compiler does not know that.

In my Visual Studio the above code snippets show the warning you encountered:
BC42019: Operands of type Object used for operator '<'; runtime errors could occur.

To get rid of the warning we add a type cast, like this with Cint():
If CInt(dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value) > 400 Then

Or another way to tell the compiler that we expect an integer, with Integer.Parse().
If Integer.Parse(dgv_config.Item(dgv_config.Columns("tsamp").Index, rowindex).Value) > 400 Then

By the way, the warning did not appear in my Visual Studio until I enabled the 'Late binding; call could fail at run time' warning configuration on the Project settings - Compile page.

  • Related