Vb.net dims in buttons turning to 0 - vb.net

I have this snippet from my code
Private Sub BtnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOne.Click
Dim ownerNum As Integer 'sets variable
ownerNum = Ownerfnc(Indicatorbtn, ownerNum) 'gives variable a number
End Sub
Function cntOwner(ByRef indicator As Object, ByRef old As Integer) As Integer
If indicator.FillColor = Color.Transparent Then
indicator.FillColor = Color.green
Return player
Else
Return old
End If
End Function
when i click the button it sets the variable to the correct number but if i click it again it sets it back to 0 is there a way to stop it from doing it?
Thanks

Declare your variable globally (outside procedure) to persist it's value.
At the moment, your variable declared locally within procedure. That way it will be recreated -hence get reset to default value- every time the procedure called. For reference, read this : MSDN - Scope in Visual Basic.

Thanks for the answers, needed to explain a bit more that i have 42 different variables that where in 42 different button clicks.
The answer was to just put static instead of dim and that worked fine for anyone that was looking for a solution like this

you should declare your variable outside the events of button click. every time you you click the button the value of ownerNum is reseting. try dis code
Dim ownerNum As Integer 'sets variable
Private Sub BtnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOne.Click
'now every time you click the ownerNum is not reseting.
ownerNum = Ownerfnc(Indicatorbtn, ownerNum) 'gives variable a number
End Sub
Function cntOwner(ByRef indicator As Object, ByRef old As Integer) As Integer
If indicator.FillColor = Color.Transparent Then
indicator.FillColor = Color.green
Return player
Else
Return old
End If
End Function

Related

vb.net why control doesn't return to original caller?

I have made researched but none of them related to my question in VB.net.
I don't know why after calling to other subs, they don't return to the original caller in Form_Load()
In the form_load, I call this sub:
Public Sub frm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To dt.Rows.Count - 1
Call calculateCounts(dt.Rows(i).Item(0)) 'call sub and pass the parameter
Next
End Sub
Public Sub calculateCounts(ByVal st as string)
'In this sub, I calculate the counts for a 2D array and pass it to another sub procedure
DisplayData(aryRow, st)
End sub
Public DisplayData(ByRef aryRow(,) as integer, ByVal st as string)
'This sub display data
End Sub
After it runs through the first time, display data correctly for the "st" parameter, it doesn't return to the original caller (form_load) to proceed to the next row. Do you know what is wrong here and what is the alternative way to fix it? thank you in advance for your help.

How to get selected items from listbox from vb.net

I'm using ListBox to display some value, it works properly but when I am trying to get the selected item from the list box it shows an error null reference error.
Below is my code that I have written to get values from ListBox:
For i As Integer = 0 To lsttasks.SelectedItems.Count - 1
userTaskDtlSrNo = Val(lsttasks.SelectedItems(i).ToString())
If userTaskDtlSrNos <> "" Then userTaskDtlSrNos &= ","
userTaskDtlSrNos &= userTaskDtlSrNo
Next
Can anyone tell me what's wrong with this code?
You don't need the Val() function there
Don't forget to declare Dim userTaskDtlSrNo as String
Use: userTaskDtlSrNo = lsttasks.SelectedItems(i).ToString()
I believe your assigning a string to a integer,
declare userTaskDtlSrNo as String, then use
userTaskDtlSrNo = Val(lsttasks.SelectedItems(i).ToString())
if you need to change userTaskDtlSNo to an integer after then just use
Dim intUserTask As Integer
Integer.TryParse(userTaskDtlSrNo, intUserTask)
to assign a new variable with same value as an integer, i dont know the rest of your code but i see no reason why this would not solve your problem. :-)
This can be way easier than it looks.
If you want to delete an object that is selected:
'let recips be the listbox name
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Recips.Items.Remove(Recips.SelectedItem)
End Sub
If you want to get the selected item (like for setting it to a string):
'let pie be a string variable, and recips to be the listbox again respectively
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
pie = Recips.selectedItem
End Sub
I hope this was enough for you, I'm not sure if I covered on enough information. Please comment so, if I forgot. Accept this answer if this helped.

Passing Variable from Windows form to Modal

Windows Forms, VB. I have searched the web for the correct answer to this and no dice. Either they are missing on what I am trying to accomplish or are in CSHARP making it harder for me to see what they are doing. I have a need to pass a record Id from the main windows form into a modal Dialog Load Event.. I have tried throwing a with param in but then I have to change the Load event params and vb flags it.. I am trying to pass the value of _CurrentProp which is an integer into the dialog. This is the dialog constructor and the load event inside that dialog..
Private Sub PropertySettingsMenuClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PropertyDetailsToolStripMenuItem.Click
Dim _propertSettings As New PropertySettingsWindow()
_propertSettings.ShowDialog()
End Sub
Private Sub PropertySettings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim _properties As New List(Of property_info)
_properties = db.property_info.ToList
For Each a In _properties
If Not p_settingsCityList.Items.Contains(a.city) Then
p_settingsCityList.Items.Add(a.city)
End If
Next
For Each b In _properties
If Not p_settingsPropertyList.Items.Contains(b.property_Name) Then
p_settingsPropertyList.Items.Add(Convert.ToString(b.idProperties) + " -- " + b.property_Name)
End If
Next
p_settingsZipCode.ReadOnly = True
p_settings_Address.ReadOnly = True
p_settings_PropertyName.ReadOnly = True
End Sub
I am going to simply assign the value to a global variable inside the PropertySettings Class but everything I try seems to fail in one way or another... Any ideas...
Add a public property RecordID to your dialog window, then open the dialog like this
Dim _propertSettings As New PropertySettingsWindow()
_propertSettings.RecordID = 15
_propertSettings.ShowDialog()
In the dialog form you can simply access the record id with
_properties = db.property_info_by_id(RecordID).ToList
Starting with .NET Framework 4.0, you can use auto-implemented properties
Public Property RecordID As Integer
With previous versions you would have to write
Private _recordID As Integer
Property RecordID As Integer
Get
Return _recordID
End Get
Set(ByVal value As Integer)
_recordID = value
End Set
End Property

manipulating textbox variables in calculations

I have some code where I am trying to use variables in a tabpage. The first tabpage only has one text box for user entry (miles.text) and a button to do a calculation: traveltime = mileage/speed. The value from miles.text is stored into a variable called mileage while the speed used is stored in a variable called speed (me.speedtextbox.text).
Ordinarily, doing val(variable.text) works like a charm and it's not doing it in this case. When the user enters 100 for the mileage, it should be divided by 65 (the number in the database) and, therefore, the answer should be 1.53 hours. In my case, I'm getting "infinity" and whenever I do anything else with the variable, I get "when casting from a number, the value must be a number less than infinity." But it is! It's only 65 and I double-checked that the dataset said that too, which it does. Not sure why I am getting this error...thank you!
Public Class Form1
Private Property Traveltime As Decimal
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'fooDataSet.testdata' table. You can move, or remove it, as needed.
Me.TestdataTableAdapter.Fill(Me.foouDataSet.testdata)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mileage As Integer
Dim speed As Integer
mileage = Val(miles.Text)
speed = Val(Me.SpeedTextBox.Text)
traveltime = mileage / speed
txttraveltime.text = Traveltime.ToString
End Sub
Private Sub txtrate_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txttraveltime.TextChanged
End Sub
End Class
So I did a test program where it did only one thing and that was to simply read one data column in a one row database and store it to a local variable and multiply it by 1.60 except now I am getting "reference to a non-shared member requires an object reference" and it doesn't seem to recognize Me.Speed when I declare it. What am I doing wrong?
Public Class Form1
Dim Speed As Object
Dim Me.Speed As New Speed
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Speed = CDec(fooDataSet.testdataRow.Item("speed"))*1.60
Speedtextbox.text = Me.Speed.tostring
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'fooDataSet.testdata' table. You can move, or remove it, as needed.
Me.TestdataTableAdapter.Fill(Me.fooDataSet.testdata)
End Sub
End Class
Before you do anything else, you should do the following:
Open the project's properties (right-click on the Project, then select Properties)
Click on the Compile tab (left-hand side)
Select All Configurations from the dropdown menu
Select On from the Option Explicit menu.
Select On from the Option Strict menu.
Save the project
This will more than likely cause a lot of errors to be displayed, but fixing these errors will substantially improve your application's health.
Now, that that is done, the following code will fix the problems in the button click:
Dim mileage As Integer
Dim speed As Integer
If IsNumeric(Me.Miles.Text) Then
mileage = CInt(Me.Miles.Text)
End If
If IsNumeric(Me.SpeedTextBox.Text) Then
speed = CInt(Me.SpeedTextBox.Text)
End If
If speed <> 0 Then
Traveltime = CDec(mileage / speed)
Else
Traveltime = 0
End If
txtTravelTime.Text = Traveltime.ToString
However, the code as you have it will produce correct results, so there must be something else amiss. Try the above first and if there are still issues, you can update your question with the details.
I would implement the calculation in a separate class and then use object-binding. Here is how the travel time calculator would look like:
Imports System.ComponentModel
Public Class TraveltimeCalculator
Implements INotifyPropertyChanged
Private _miles As Double
Public Property Miles() As Double
Get
Return _miles
End Get
Set(ByVal value As Double)
If _miles <> value Then
_miles = value
OnPropertyChanged("Miles")
OnPropertyChanged("Traveltime")
End If
End Set
End Property
Private _speed As Double
Public Property Speed() As Double
Get
Return _speed
End Get
Set(ByVal value As Double)
If _speed <> value Then
_speed = value
OnPropertyChanged("Speed")
OnPropertyChanged("Traveltime")
End If
End Set
End Property
Public ReadOnly Property Traveltime() As Double
Get
Return If(_speed = 0.0, 0.0, _miles / _speed)
End Get
End Property
#Region "INotifyPropertyChanged Members"
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub OnPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
#End Region
End Class
In Visual Studio, add a data source in the Data Sources panel. Choose "Object" and then select the TraveltimeCalculator (it has to be compiled, before you can do that). Now you can drag the speed, mileage and travel time fields from the data sources panel to your form. All the wire-up will happen automatically. VS automatically inserts a BindingSource and a navigator into your form. You will not need the navigator and can safely remove it. The only thing you still have to do is to add the following code in the form load event handler or in the form constructor:
Private Sub frmTravelTime_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TraveltimeCalculatorBindingSource.DataSource = New TraveltimeCalculator()
End Sub
When you enter speeds and mileages, the travel time textbox will automatically be updated. Non-numeric entries will automatically be rejected and all the text-number conversions happen automatically.
I discovered what the problem was.
To store a field from a one-line database to a local variable for calculations, apparently it has to happen in the form1_load event, after the dataadapter fill statement, like so:
Me.TestdataTableAdapter.Fill(Me.foouDataSet.testdata)
speed = Me.fooDataSet.testdata(0).speed
and just DIM speed as Decimal after the Public Class line. The same could be done for any other field you want to work with in a similar kind of single datarow:
yourvarname = Me.yourdatasetname.yourtablename(0).the_database_field_you_want_to_fetch
(Wow! Did I just write something textbooky? LOL)
Then, after the button click, to do a calculation, it is:
traveltime = CDec(miles.Text/ speed)
txttraveltime.Text = traveltime.ToString
making sure to DIM traveltime as Decimal.
Works! The problem was the (0) to indicate row 0 (because it's only one row.) Thank you everyone for your help, especially Competent_Tech. I learned something and I'm happy that I could get back to you guys and share.

Search ListBox elements in VB.Net

I'm migrating an application from VB6 to VB.Net and I found a change in the behavior of the ListBox and I'm not sure of how to make it equal to VB6.
The problem is this:
In the VB6 app, when the ListBox is focused and I type into it, the list selects the element that matches what I type. e.g. If the list contains a list of countries and I type "ita", "Italy" will be selected in the listbox.
The problem is that with the .Net version of the control if I type "ita" it will select the first element that starts with i, then the first element that starts with "t" and finally the first element that starts with "a".
So, any idea on how to get the original behavior? (I'm thinking in some property that I'm not seeing by some reason or something like that)
I really don't want to write an event handler for this (which btw, wouldn't be trivial).
Thanks a lot!
I shared willw's frustration. This is what I came up with. Add a class called ListBoxTypeAhead to your project and include this code. Then use this class as a control on your form. It traps keyboard input and moves the selected item they way the old VB6 listbox did. You can take out the timer if you wish. It mimics the behavior of keyboard input in Windows explorer.
Public Class ListBoxTypeAhead
Inherits ListBox
Dim Buffer As String
Dim WithEvents Timer1 As New Timer
Private Sub ListBoxTypeAhead_KeyDown(sender As Object, _
e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.A To Keys.Z, Keys.NumPad0 To Keys.NumPad9
e.SuppressKeyPress = True
Buffer &= Chr(e.KeyValue)
Me.SelectedIndex = Me.FindString(Buffer)
Timer1.Start()
Case Else
Timer1.Stop()
Buffer = ""
End Select
End Sub
Private Sub ListBoxTypeAhead_LostFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.LostFocus
Timer1.Stop()
Buffer = ""
End Sub
Public Sub New()
Timer1.Interval = 2000
End Sub
Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
Buffer = ""
End Sub
End Class
As you probably know, this feature is called 'type ahead,' and it's not built into the Winform ListBox (so you're not missing a property).
You can get the type-ahead functionality on the ListView control if you set its View property to List.
Public Function CheckIfExistInCombo(ByVal objCombo As Object, ByVal TextToFind As String) As Boolean
Dim NumOfItems As Object 'The Number Of Items In ComboBox
Dim IndexNum As Integer 'Index
NumOfItems = objCombo.ListCount
For IndexNum = 0 To NumOfItems - 1
If objCombo.List(IndexNum) = TextToFind Then
CheckIfExistInCombo = True
Exit Function
End If
Next IndexNum
CheckIfExistInCombo = False
End Function