简体   繁体   中英

use input from combo box as integer in code (vb.net)

right now my code reads

Dim divisor as Integer = "10"

i have created a form with a drop-down combo box that allows a user to choose the divisor instead of it being hardwired into the code. the name of the combo box is 'divisor1'

how do i refer to the input in divisor1 to be read as the divisor? ie

Dim divisor as Integer = divisor1 'throws an error

TIA

For starters, you need to use a property on the divisor1 combo box, not the box itself. But in order to use it as an integer, you need to convert it from a string. Which should also come with some error checking, just in case the input isn't actually an integer. Something like this:

Dim divisor as Int32 = 1
If Int32.TryParse(divisor1.Text, divisor) Then
    ' Perform your logic
Else
    ' The input wasn't a valid integer, maybe show an error?
End If

What this does is initialize a default integer as 1 (normally the default might be 0, but if you're looking to divide by this number then perhaps 0 isn't the best idea), then it tries to parse the value of divisor1.Text into that integer. If it succeeds, you can continue with your code. If it fails, then the combo box didn't have a valid number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM