I have tried converting using CInt, TryParse, Convert.Int32, etc but nothing worked. I just need to display the total votes of the candidated when a button btnVote is clicked and display the result when I click btnResult. I've tried searching on the net also but still no luck so I came up to this website and hopefully I could solve my problem with my program in VB.net
Below is my code:
Public Class Presidential_Election
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
If cboCandidates.Text = "NOLI" Then
lblNoli.Text = Integer.Parse(lblNoli.Text) + 1
ElseIf cboCandidates.Text = "VAL" Then
lblVal.Text = (CInt(lblVal.Text) + 1).ToString
ElseIf cboCandidates.Text = "LESTER" Then
lblLester.Text = CInt(lblLester.Text) + 1
ElseIf cboCandidates.Text = "GWAPO" Then
lblGwapo.Text = CInt(lblGwapo.Text) + 1
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
lblNoli.Visible = True
lblVal.Visible = True
lblLester.Visible = True
lblGwapo.Visible = True
End Sub
End Class
I would set an integer counter for each candidate. Set these to 0 and then increment them as they receive a vote. When you display the results just bind the text of the label to its respective counter and make it visible. This way, you don't have to keep referencing label.text.
If you haven't set the label text to be 0 at the beginning, using CInt would definitely throw an error. You have two options :
set all labels text to 0 and keep using CInt, or
use Val()
Example :
lblGwapo.Text = Val(lblGwapo.Text) + 1
Related
i have setup a listview with the following properties:
FullRowSelect = True
GridLines = True
View = Details
HeaderStyle = Nonclickable
Multiselect = False
i have created 4 columns, and populated them with 10 rows of data. i want to get the row number every time i click on a row in the listview. i have done this as follows:
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
indexNo = ListView1.FocusedItem.Index
label1.text = indexNo.ToString
End Sub
indexNo is a publicly declared string.
when i click on a different row in the listview, i get the following error:
NullReferenceException was unhandled
Object reference not set to an instance of an object.
Make sure something is selected first:
If Not IsNothing(ListView1.FocusedItem) Then
indexNo = ListView1.FocusedItem.Index
Label1.Text = indexNo.ToString
End If
Alternatively, check the length of the SelectedIndices collection:
If ListView1.SelectedIndices.Count > 0 Then
indexNo = ListView1.SelectedIndices(0)
Label1.Text = indexNo.ToString
End If
I'm trying to pick up a combo box's selected index. This was working absolutely fine, then all of a sudden it started returning -1 no matter what item is selected
My code is:
Form Code
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged, Units.SelectedIndexChanged
'Set Transducer Type
Call References.LevListAdd()
End Sub
References Module LevListAdd Sub
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
End If
End Sub
This fills the combo box lev fine when the Man combo box item "Pulsar" is selected. I then want my users to click a button to generate some labels and stuff. The code is as such:
Button Click Code
Private Sub Generate_Click(sender As Object, e As EventArgs) Handles Generate.Click
If CheckGenerate() = False Then Exit Sub
Dim X = CheckGenerationType(Man.SelectedIndex, Lev.SelectedIndex, Level.Checked, Volume.Checked, ListBox1.SelectedIndex,
Units.SelectedIndex)
Call ParamPage(X)
End Sub
CheckGenerate simply checks that all boxes have been filled in. I pass the informtion from the form to the following function:
Public Function CheckGenerationType(Man As Integer, Lev As Integer, Level As Boolean, Volume As Boolean, TankType As Integer,
MeasurementUnit As Integer) As String
Dim M As Integer
Dim L As Integer
Dim CT As Integer
Dim TT As Integer
Dim Ms As Integer
M = Man
L = Lev
TT = TankType
Ms = MeasurementUnit
If Level = True Then
CT = 0
ElseIf Volume = True Then
CT = 1
End If
CheckGenerationType = CStr(M) + "." + CStr(L) + "." + CStr(CT) + "." + CStr(TT) + "." + CStr(Ms)
End Function
When the lev.selectedindex parameter arrives at this function, it reads -1. Even if the user has selected any of the 3 items. Can anyone explain why this is happening?
I've just tried your code. I get the same result (-1 in lev.SelectedIndex) and this was because jumped using tab through the controls my when i'm hitting the Man or Units Combobox it runs the LevListAdd() and then clears the Lev-ComboBox because of Form1.Lev.Items.Clear().
You should think about your call Man_SelectedIndexChanged_1 or maybe just use something like this:
Public Sub LevListAdd()
If Form1.Man.Text = "Pulsar" Then
Form1.Lev.Items.Clear()
instead of
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
And you should separate the calls from the man and unit ComboBoxes.
Private Sub Unit_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Units.SelectedIndexChanged
' Do something
End Sub
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged
Form1.Lev.Items.Clear()
Select Case Form1.Man.Text
Case "Pulsar"
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
Case "animals"
With Form1.Lev.Items
.Add("dogs")
.Add("cats")
.Add("birds")
End With
End Select
End Sub
I've looked all over the web for an answer to this, and been unable to replicate the bug myself, and somehow the textbox is appearing to be transparent and unable to be clicked; however it seems that if you set the "Text =" property to have a message in it, the textbox works fine.
I've looked at the properties and the code multiple times, nothing seems to be off. There's no calling of the textbox to be transparent, and nothing I've seen that would stop it from accepting user input.
The... "broken" code is:
Public Class GuessingGame
Const MIN As Integer = 1
Const MAX As Integer = 50
Private Sub btnCheckGuess_Click(sender As System.Object, e As System.EventArgs) Handles btnCheckGuess.Click
Randomize()
Static secretNumber As Integer = Int((MAX - MIN + 1) * Rnd() + MIN)
Static Count = 0
Dim guess As Integer
Count = Count + 1
guess = Val(Me.txtPlayerGuess.Text)
If guess < MIN Or guess > MAX Then 'invalid guess
MessageBox.Show("Guess out of range")
ElseIf guess = secretNumber Then
Me.lblMessage.Text = "You guessed it!" 'correct
MessageBox.Show(Count)
Else
Call GiveHint(secretNumber, guess)
End If
End Sub
Private Sub txtPlayerGuess_TextChanged(sender As System.Object, e As System.EventArgs)
'Clear the current answer when the user begins to type a new value
Me.lblMessage.Text = Nothing
End Sub
Private Sub GiveHint(firstNum As Integer, ByVal secondNum As Integer)
If firstNum > secondNum Then
MessageBox.Show("Too low.")
Else
MessageBox.Show("Too high.")
End If
End Sub
End Class
Anyone have any ideas as to what is causing this and how to fix it?
I'm creating an array of checkboxes on a form dynamically; the code that creates the array looks like this:-
checkbox_array(count_of_checkboxes) = New CheckBox
if (count_of_checkboxes = 0) Then
checkbox_array(count_of_checkboxes).Top = specimen_checkbox.Top
checkbox_array(count_of_checkboxes).Left = specimen_checkbox.Left
else
checkbox_array(count_of_checkboxes).Top = checkbox_array(count_of_checkboxes - 1).Top + vertical_offset
checkbox_array(count_of_checkboxes).Left = checkbox_array(count_of_checkboxes - 1).Left + horizontal_offset
End If
my_panel.Controls.Add(checkbox_array(count_of_checkboxes))
AddHandler checkbox_array(count_of_checkboxes).MouseClick, cbxSpecimen_CheckedChanged
checkbox_array(count_of_checkboxes).Name = someValue
checkbox_array(count_of_checkboxes).Text = someValue
checkbox_array(count_of_checkboxes).Enabled = true
checkbox_array(count_of_checkboxes).Visible = true
checkbox_array(count_of_checkboxes).Show()
This works fine and dandy on one form. However, I am using the same code on a form which is derived from a base form, and running into a problem, in that the object returned in the sender parameter, although clearly a checkbox with a recognisable name, isn't any of the checkboxes in the array.
I verified this with:-
Private Sub cbxSpecimen_CheckedChanged( sender As System.Object, e As System.EventArgs) Handles cbxSpecimen.CheckedChanged
For i As Integer = 0 To checkbox_array.GetUpperBound(0) - 1
If checkbox_array(i).Equals(sender) Then
// set a breakpoint here
End If
Next i
End Sub
Can anyone shed any light on why this should work on a normal form, but not a derived-class form?
I verified this with:-
Private Sub cbxSpecimen_CheckedChanged( sender As System.Object, e As System.EventArgs)
Handles cbxSpecimen.CheckedChanged
For i As Integer = 0 To checkbox_array.GetUpperBound(0) - 1
If checkbox_array(i).Equals(sender) Then
// set a breakpoint here
End If
Next i
End Sub
Why checkbox_array.GetUpperBound(0) - 1? This will skip the last element in the array. Try:
For i As Integer = 0 To checkbox_array.GetUpperBound(0)
If checkbox_array(i).Equals(sender) Then
// set a breakpoint here
End If
Next i
Or
For i As Integer = 0 To checkbox_array.Length - 1
...
I have managed to get this to work by refilling the array of checkboxes inside the click event:-
Private Sub cbxSpecimen_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxSpecimen.CheckedChanged
For i As Integer = 0 To check_boxes.GetUpperBound(0)
If check_box_array(i).Name = CType(sender, CheckBox).Name And
Not check_box_array(i).Equals(sender) Then
check_box_array(i) = CType(sender, CheckBox)
End If
Next i
' do useful work
End Sub
After the check box on the form has been stuffed back into the array, it remains there (so the second invokation for the same checkbox doesn't insert into the array a second time).
This seems like a ghastly hack to me, but I'll go with it for the time being.
I'm learning VB.NET.
I've a problem with DataGridView component when trying to set the value of the CurrentCell.
What i'm trying to do is :
I've a DataGridView With values.
I want to make a button in my forms and when clicking on it I want to change the selection from the current row to the next. To explain more, by clicking my Button I want to simulate the effect of a mouse click on a DataGridview.
I hope you can help me,
Thanks!
Maybe something like this:
If DataGridView1.RowCount > 0 Then
Dim MyDesiredIndex As Integer = 0
If DataGridView1.CurrentRow.Index < DataGridView1.RowCount - 1 Then
MyDesiredIndex = DataGridView1.CurrentRow.Index + 1
End If
DataGridView1.ClearSelection()
DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)
DataGridView1.Rows(MyDesiredIndex).Selected = True
End If
Note 1: maybe these two lines are not necessary. I havenĀ“t proved it
DataGridView1.ClearSelection()
DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)
Note 2: note that if we are in the last row, it goes to first
You need to set the particular row's Selected property to true. I think the VB would be something like this:
someDGV.Rows(index).Selected = True
If your data grid is bound to a BindingSource, it is better to change the position there:
Object key = Convert.ToInt32(cdr["WordList"]);
int itemFound = lexiconNamesBindingSource.Find("ID_Name", key);
lexiconNamesBindingSource.Position = itemFound;
...and you might need to finish it off with:
lexiconNamesBindingSource.ResetBidings();
(This is an old thread, but I found it, so someone else might find this useful)
Just use the BindingSource.MoveNext() and BindingSource.MovePrevious() methods.
You could do it this way:
If DataGridView1.CurrentRow.Index < DataGridView1.Rows.Count Then
DataGridView1.Rows(DataGridView1.CurrentRow.Index + 1).Selected = True
End If
To get the selected row, you should use SelectedRows(0).Index inspite of CurrentRow. Because if you programmaticaly make a row as selected, then next time you will find 0 in CurrentRow.Index. So It would be like :
If DataGridView1.SelectedRows(0).Index < DataGridView1.RowCount - 1 Then
MyDesiredIndex = DataGridView1.SelectedRows(0).Index + 1
End If
DataGridView1.Rows(MyDesiredIndex).Selected = True
expanding on the answer above which is perfect considering I spent at least 4 hours loooking for this.
and assuming that your datagridview is called dgvDevices... this code will handle the event in which you go outbounce as you move back and forward on your rows
Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrev.Click
Try
dgvDevices.ClearSelection()
Dim currentr As Integer = dgvDevices.CurrentCell.RowIndex
dgvDevices.CurrentCell = dgvDevices.Rows(currentr - 1).Cells(0)
dgvDevices.Rows(currentr - 1).Selected = True
Catch ex As Exception
dgvDevices.CurrentCell = dgvDevices.Rows(0).Cells(0)
dgvDevices.Rows(0).Selected = True
End Try
End Sub
Private Sub btnForw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForw.Click
Try
dgvDevices.ClearSelection()
Dim currentr As Integer = dgvDevices.CurrentCell.RowIndex
dgvDevices.CurrentCell = dgvDevices.Rows(currentr + 1).Cells(0)
dgvDevices.Rows(currentr + 1).Selected = True
Catch ex As Exception
dgvDevices.CurrentCell = dgvDevices.Rows(dgvDevices.RowCount - 1).Cells(0)
dgvDevices.Rows(dgvDevices.RowCount - 1).Selected = True
End Try
End Sub
Besides Javiers correct answer, if you're using BindingSource for your datagridview then it will be better to change selected item from binding source rather than using datagridview.CurrentCell:
' Example Definitions
Dim bsExample As New BindingSource
Dim dgv As New DataGridView
dgv.DataSource = bsExample
' Example code to change current row position
Dim desiredIndex As Integer = 10
bsExample.Position = desiredIndex
Private Sub DGW2_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DGW2.DataBindingComplete
Dim mygrid As DataGridView
mygrid = CType(sender, DataGridView)
mygrid.ClearSelection()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If DataGridView1.Rows.Count - 1 > 0 Then
For i As Integer = 0 To DataGridView1.Rows.Count - 1 Step +1
If DataGridView1.Rows.Count - 1 > 0 Then
DataGridView1.Rows.RemoveAt(0)
End If
Next
Else
End If
End Sub
Easy with Extensions
Imports System.Runtime.CompilerServices
Module Extensions
''' <summary>
''' Select the Row(Index)
''' </summary>
''' <param name="Dgv">The DataGridView</param>
''' <param name="Index">The Row Index (0 First)</param>
''' <param name="ScroolToTop">If True scrool the row to top</param>
''' <returns>True if no error or False if something went wrong</returns>
' USE: if not DataGridView1.GoToRow(30) then MsgBox("Something went wrong!)
<Extension()>
Public Function GoToRow(Dgv As DataGridView, Index As Integer, Optional ScroolToTop As Boolean = True) As Boolean
If Index > -1 And Index < Dgv.Rows.Count - 1 Then
With Dgv
.ClearSelection()
.Rows(Index).Selected = True
If ScroolToTop Then .FirstDisplayedScrollingRowIndex = Index
End With
Return True
End If
Return False
End Function
End Module
I have DataGridView like that :
| ID | Name |
|:---|:-----:|
| 1 | Samir |
I search by 'Name' using this code :
Private Sub GunaButton6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GunaButton6.Click
Dim temp As Integer = 0
For i As Integer = 0 To Me.Listofclient.RowCount - 2
If Me.Listofclient.Rows(i).Cells(1).Value.ToString = EDSearch.Text Then
Me.Listofclient.ClearSelection()
Me.Listofclient.Rows(i).Selected = True
temp = 1
End If
Next
If temp = 0 Then
MsgBox("Item not found")
End If
End Sub