Home > Enterprise >  VB.NET PictureBox showed the wrong image
VB.NET PictureBox showed the wrong image

Time:09-15

I am experimenting to show device's battery percentage with sets of image that's shown on a PictureBox. Here's my code (I put it on a timer)

`

Dim psBattery As PowerStatus = SystemInformation.PowerStatus
        Dim perFull As Single = psBattery.BatteryLifePercent
        Dim perFull2 As Single = perFull * 100
        If psBattery.PowerLineStatus = PowerLineStatus.Online Then
            If perFull2 > 96 Then
                PBBatt.Image = My.Resources._100p
            ElseIf 76 < perFull2 < 95 Then
                PBBatt.Image = My.Resources._87p
            ElseIf 51 < perFull2 < 76 Then
                PBBatt.Image = My.Resources._75p
            ElseIf 38 < perFull2 < 51 Then
                PBBatt.Image = My.Resources._50p
            ElseIf 27 < perFull2 < 38 Then
                PBBatt.Image = My.Resources._37p
            ElseIf perFull2 < 26 Then
                PBBatt.Image = My.Resources._25p
            End If
        ElseIf psBattery.PowerLineStatus = PowerLineStatus.Offline Then
            If perFull2 > 96 Then
                PBBatt.Image = My.Resources._100up
            ElseIf 76 < perFull2 < 95 Then
                PBBatt.Image = My.Resources._87up
            ElseIf 51 < perFull2 < 76 Then
                PBBatt.Image = My.Resources._75up
            ElseIf 38 < perFull2 < 51 Then
                PBBatt.Image = My.Resources._50up
            ElseIf 27 < perFull2 < 38 Then
                PBBatt.Image = My.Resources._37up
            ElseIf perFull2 < 26 Then
                PBBatt.Image = My.Resources._25up
            End If
        End If

`

The problem I got is that the PictureBox only show correct image when my battery percentage is > 96 and < 26, other than that it showed _87up/_87p

I tried to use OR operator (So instead of 76 < perFull2 < 95 , I changed it to perFull2 > 76 OR perFull2 < 95 and changed the type of perFull and perFull2 to Integer , but it didn't work, the result is still the same as previous code.

So, how can I mitigate this issue?

CodePudding user response:

you need to cast the numbers to single using CSng also you don't need to provide a range for your conditions, see the following code.

Dim x As Single = 88
    If psBattery.PowerLineStatus = PowerLineStatus.Online Then
        If x > CSng(96) Then
            MessageBox.Show("96")
        ElseIf perFull2 > CSng(76) Then
            MessageBox.Show("76")
        ElseIf perFull2 > CSng(51) Then
            MessageBox.Show("51")
        ElseIf perFull2 > CSng(38) Then
            MessageBox.Show("38")
        ElseIf perFull2 > CSng(27) Then
            MessageBox.Show("27")
        Else
            MessageBox.Show("26")
        End If
    End If
  • Related