Converting a combobox to int - vb.net

I'm trying to convert a string from a combobox to a usable integer format
my relevant piece of code:
Dim intDays As Integer
intDays = Convert.ToInt32(cboDays.Text)
lblDays.Text = intDays
After selecting my number for days, the label should change to the value for days selected if it had successfully been converted to an integer but it did not, so I am clearly missing something

If you have your combobox set to DropDownList, then the correct code is:
lblDays.Text = CInt(cboDays.SelectedItem.ToString)

you need to use the combobox SelectedIndexChanged to do this otherwise your code will not get called.
Then your code works.
Double click there to make the event.
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboDays.SelectedIndexChanged
Dim intDays As Integer
intDays = Convert.ToInt32(cboDays.Text)
lblDays.Text = intDays
End Sub
If lstRentalType.SelectedIndex <> -1 Then
'code ......
Else
'msgbox.....
End If

Related

'Conversion from string "" to type 'Double is not valid.'

Just started doing Visual Basic, and am trying to make a time converter. I'm aware my code may be very inefficient or impractical, but I'm trying to make a part of the program where you type in your number of minutes into the text box as opposed to using the scrollbar. However, when the text box is empty the program crashes and throws the 'Conversion from string "" to type 'Double is not valid.' error. Code is below. The line where the error is shown is highlighted in red.
Public Class timeConverter
Private Sub scrollBar_Scroll(sender As Object, e As ScrollEventArgs) Handles scrollBar.Scroll
Dim minuteBoxInt As Integer 'Declaring variables'
Dim hourBoxInt As Integer
Dim minuteBox2Int As Integer = scrollBar.Value Mod 60
minuteBox.Text = scrollBar.Value() 'The scrollbar value will change with the minute box text'
minuteBoxInt = minuteBox.Text() 'Make the minuteBox associated with the minuteBoxInt variable'
hourBoxInt = Math.Floor(minuteBoxInt / 60) 'Rounds the decimal when the minuteBoxInt reaches 60'
hourBox.Text = hourBoxInt 'Makes the hourBox associated with the hourBoxInt variable'
minuteBox2.Text() = minuteBox2Int 'Makes the minuteBox2 associated with the minuteBox2Int variable'
End Sub
Private Sub minuteBox_TextChanged(sender As Object, e As EventArgs) Handles minuteBox.TextChanged
hourBox.Text = minuteBox.Text() / 60
End Sub
End Class```
To check user input (or lack of input) use .TryParse. Pass it a string and a variable of the type you are looking for. The .Text property of a TextBox is a string and here we have declare a variable, minutes, which will be filled with the parsed value of the string if the parse is successful. .TryParse returns a Boolean so it can be used in an If statement.
Private Sub minuteBox_TextChanged(sender As Object, e As EventArgs) Handles minuteBox.TextChanged
Dim minutes As Integer
If Integer.TryParse(minuteBox.Text, minutes) Then
hourBox.Text = (minutes / 60).ToString
Else
MessageBox.Show("Please make a valid entry in the minutes box.")
End If
End Sub

Alternative Process

I have 2 buttons and a DataGridView with 2 Columns (0 & 1).
The 1st button transfers a randomized cell from the Column(1) to a TextBox. Then, it stores that Cell in variable (a), plus the cell that opposites it in variable (b).
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rnd As New Random
Dim x As Integer = rnd.Next(0, Form1.DataGridView1.Rows.Count)
Dim y As Integer = 1
Dim a As String = Form1.DataGridView1.Rows(x).Cells(y).Value
Dim b As String = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
The 2nd button, however, is supposed to compare if another TextBox's text has the same string variable (b) has as Strings. Now, if so, then it has to display a certain message and so on...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox4.Text = b Then '<<< ISSUE HERE!
MsgBox("Correct! ^_^")
ElseIf TextBox4.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub
The problem is that the variable (b) is surely not shared across the two "private" subs. And so, there is NOTHING to compare to in the 2nd button's sub! I presume that the solution here is to split the "randomization process" into a separate function, then execute it directly when the 1st button gets activated. Furthermore, that function's variables have to be SHARED somehow, and I certainly don't know how!
Thanks for Mr. Olivier, the code has been improved significantly! Yet, I still encounter a "wrong" comparison issue, somehow!
Dim RND As New Random
Dim x As Integer
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
x = RND.Next(0, Form1.DataGridView1.Rows.Count)
tbxRoll.Text = GetCell(x, 1)
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If tbxSubmit.Text = GetCell(x, 0) Then
MsgBox("Correct! ^_^")
ElseIf tbxSubmit.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub</code>
Well, unbelievably, I read a guide about "comparison operations" in VB.net and tried out the first yet the most primal method to compare equality - which was to use .Equals() command - and worked like a charm! Thank God, everything works just fine now. ^_^
If tbxSubmit.Text.Equals(GetCell(x, 0)) Then
Alright now... This is going to sound weird! But, following Mr. Olivier's advise to investigate "debug" the code, I rapped the string I'm trying to compare with brackets and realized that it's been outputted after a break-line space! So, I used the following function to remove the "white-space" from both of the comparison strings! And it bloody worked! This time for sure, though. ^_^
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
If RemoveWhitespace(tbxSubmit.Text) = RemoveWhitespace(GetCell(x, 0)) Then
Turn the local variables into class fields.
Dim rnd As New Random
Dim x As Integer
Dim y As Integer
Dim a As String
Dim b As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
x = rnd.Next(0, Form1.DataGridView1.Rows.Count)
y = 1
a = Form1.DataGridView1.Rows(x).Cells(y).Value
b = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
These fields can now be accessed from every Sub, Function and Property.
Of course Button3_Click must be called before Button2_Click because the fields are initialized in the first method. If this is not the case then you should consider another approach.
Create a function for the Cell access
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) _
As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
And then compare
If TextBox4.Text = GetCell(x, y - 1) Then
...
And don't store the values in a and b anymore. If y is always 1 then use the numbers directly.
If TextBox4.Text = GetCell(x, 0) Then
...
One more thing: give speaking names to your buttons in the properties grid before creating the Click event handlers (like e.g. btnRandomize). Then you will get speaking names for those routines as well (e.g. btnRandomize_Click).
See:
- VB.NET Class Examples
- Visual Basic .NET/Classes: Fields

System.InvalidCastException when textboxes are empty

When I type in the first text box, leaving the other text boxes empty, I get this error:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll"
Public Class myProject_P2
Public Sub CostPerKWH_TextChanged(sender As Object, e As EventArgs) Handles CostPerKWH.TextChanged
Dim CostPerkwh_Value As Integer = CostPerKWH.Text
Dim Appliancekwh_Value As Integer = ApplianceKWH.Text
Dim HourPerDay_Value As Integer = HoursPerDay.Text
Dim EnergyConsumption_Value As Integer = EnergyConsumptio.Text
EnergyConsumption_Value = CostPerkwh_Value * Appliancekwh_Value * HourPerDay_Value
End Sub
End Class
I don't really know the flow of your program but if your problem is only that error stated in your question which is System.InvalidCastException then try the code I pasted below.
Before anything else, the reason why it throws that error is perhaps you typed on the first field leaving others empty which your first field was programmed that upon text change, the values of other fields will be passed on or assigned to an integer variable. Since they are empty, therefore, the value passed on were "" values or empty string values. String values assigned to an integer will surely cause an error. Try to validate before passing the values and I suggest not to put the assigning of values in your text change, rather, try adding a button and add there the codes. Upon button click, the process goes on like this:
Dim CostPerkwh_Value As Integer
Dim Appliancekwh_Value As Integer
Dim HourPerDay_Value As Integer
Dim EnergyConsumption_Value As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If IsNumeric(CostPerKWH.Text) And IsNumeric(ApplianceKWH.Text) _
And IsNumeric(HoursPerDay.Text) And IsNumeric(EnergyConsumptio.Text) Then
CostPerkwh_Value = CostPerKWH.Text
Appliancekwh_Value = ApplianceKWH.Text
HourPerDay_Value = HoursPerDay.Text
EnergyConsumption_Value = EnergyConsumptio.Text
EnergyConsumption_Value = CostPerkwh_Value * Appliancekwh_Value * HourPerDay_Value
MsgBox(EnergyConsumption_Value)
Else
MsgBox("Some inputs are not in numeric.")
End If
End Sub
another solution would be:
if TryCast(Textboxt1.text, integer) then
' do something
end if
MSDN TryCast Documentation

Reading the value of the cell

I have some DataGridView code written in vb.net. (Nothing is attached to a datasource.)
The 4th column is a checkboxCell. How do I detect if that checkBox is checked or unchecked?
This code strangely reports TRUE or FALSE at random times. It even turns ON the checkbox in rows other than the row I clicked in.
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim whichGrid As DataGridView = CType(sender, DataGridView)
Dim rowClicked As Int16 = e.RowIndex
Call MsgBox(rowClicked & vbCrLf & whichGrid.Rows(rowClicked).Cells(4).Value)
End Sub
All the other examples I've looked at here (and elsewhere) don't seem to help. Their solutions are always:
Just check the cell's VALUE.
Just learn c#, and learn to convert it to vb.net.
Just check VALUE for nothing, or null, or "", or all of those.
Convert VALUE to a bool.
Attach it to a datasource instead.
Set TrueValue and FalseValue.
I've tried countless other methods, none seem to actually get the checkbox ON/OFF value in vb.net.
Cast the cell's value to a Boolean:
Dim RowIndex As Integer = ...
Dim ColumnIndex As Integer = ...
Dim IsTicked As Boolean = CBool(DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value)
If IsTicked Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If

Capturing value of DataGridView CheckBox in VB.Net

I have a datagridview (unbound). Fields are Name, Family Name and Phone No and a checkbox colum.
There are ten rows in that DataGridView.
There is an OK button
I need to get message of showing which rows user has checked. The message should appear when user clicks on the OK button. There could be several messages, checking each row one by one, in a loop.
I am not able to get this message. I tried following code in OK button :
Dim strCB As String = dgvChooseQs.Rows(0).Cells(3).Value.ToString
Cell(3) is my checkbox. Do not consider Rows(0), at the moment I am just checking value at row 0
Thanks for your help.
Furqan
Do not use the cell index. Your checkbox column must have a name so you should use it.
Otherwise, what you want to do would be something like this
For each oRow as DataGridViewRow in dgvChooseQs.Rows
If oRow.Cells("ColNamE").Value = True then
'do whatever you need to do.
End if
Next
If you feel you need to cast the column, then you can use CType, but the type is DataGridViewCheckBoxCell, not CheckBox.
You need to do something like this:
if ctype(dgvChooseQs.Rows(0).findcontrol("whateverYourCheckBoxIsNamed"), checkbox).checked then
'throw the message
end if
You may cast the cell value to Boolean, and then check it, as follows:
Dim RowIndex As Integer = ...
Dim ColumnIndex As Integer = ...
Dim IsTicked As Boolean = CBool(DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value)
If IsTicked Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
Only the third example worked for me but I had to add a Timer
Private Sub DgvElencoFile_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DgvElencoFile.CellClick
'Variabili gestione programma
Dim numerocolonnaSelezionata As Integer
Dim numeroColonnaSelezionataPerDowonload As Integer
Dim numeroRigaSelezionata As Integer
numeroRigaSelezionata = e.RowIndex
NumerocolonnaSelezionata = e.ColumnIndex
If NumeroRigaSelezionata < 0 Then
ClaFunzSgnSon.SegnaleSonoro(ClaFunzSgnSon.EnTipoSgnSon.ErroreImpostazioneDati)
GoTo FineSubFunz
End If
numeroColonnaSelezionataPerDowonload = -1
If DgvElencoFile.Rows(numeroRigaSelezionata).Cells(ClnDownLoad.Name).Selected Then numeroColonnaSelezionataPerDowonload = numerocolonnaSelezionata
If numeroColonnaSelezionataPerDowonload >= 0 Then
TimVisCheckDownLoad.Start()
End If
FineSubFunz:
End Sub
Private Sub TimVisCheckDownLoad_Tick(sender As Object, e As EventArgs) Handles TimVisCheckDownLoad.Tick
TimVisCheckDownLoad.Stop()
Dim isTickedOn = CBool(DirectCast(DgvElencoFile.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
If isTickedOn Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
End Sub
I found a simple solution.
Just change the cell focus after click on cell.
Private Sub DGV_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellContentClick
If e.ColumnIndex = "Here checkbox column id or name" Then
DGV.Item(e.ColumnIndex, e.RowIndex + 1).Selected = True
'Here your code
MsgBox DGV.Item(e.ColumnIndex, e.RowIndex).Value
End If
End Sub
Don't forget to check if the column of your (ckeckbox + 1) index exist.
Set type of grid in dataGridView to 'DataGridViewCheckBoxXColumn' instead of DataGridViewCheckBoxColumn.
all problems will be solved
The post is old but it can help in need:
You have these three properties after casting your cell:
Private Sub YourDataGridView_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles YourDataGridView.CellMouseClick
Dim b, b1, b2 As Boolean
b = DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellValueChanged
b1 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
b2 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditedFormattedValue)
End Sub
it's a long time since this question was sent, but can be useful this answer to anybody with the same issue. In my case, I used (I'm using your notation):
dgvChooseQs.Item(6, vCont).State
where 6 is the checkbox column number, in my case column 6. vCont is an iteration counter in a FOR NEXT loop. If State equals 32, checkbox was checked, else State will be zero. I hope this can be of help.