VB.Net how to prevent listbox firing selectedindexchanged selectedvaluechanged on load - vb.net

Help, When I set datasource to listbox it fires selectedindexchanged and selectedvaluechanged. How can I prevent this because this resets my value to the first item all the time
Dim SQLString As String
Dim dt As New DataTable
Dim Properties As New Properties
SQLString = "select v.attributevalue,v.value"
SQLString += " from Table "
SQLString += " Where v.attributename ='new_vehicle'"
SQLString += " order by v.value"
getDataBySQL(SQLString, dt)
lstCategory.ValueMember = "attributevalue"
lstCategory.DisplayMember = "value"
lstCategory.DataSource = dt
Dim i As Integer = ReadDataFromDatabase
If i <> 0 Then
lstCategory.SelectedValue = i
End If
Private Sub lstCategory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCategory.SelectedIndexChanged
End Sub
Private Sub lstCategory_SelectedValueChanged(sender As Object, e As EventArgs) Handles lstCategory.SelectedValueChanged
SetDataToDatabase(lstCategory.SelectedValue.ToString)
End Sub
also when I set valuemember to the listbox it fires selectedvaluechanged.
Essentially I want to read the database value so when I have the listbox loaded it switch the selected value to what is the value in the database
Variable i is the selectedValue I want.

Typically when I develop an application, I will create a Boolean variable called IsLoading and set it to false by default. I will flag this as true before any code that may be loading data and mark it as false when completed. In most cases this is in my Page Load.
Private Sub Form_Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
IsLoading = True
'Code to load my data goes here
IsLoading = False
End Sub
I will then add it to my dropdowns like so:
Private Sub lstCategory_SelectedValueChanged(sender As Object, e As EventArgs) Handles lstCategory.SelectedValueChanged
If Not IsLoading Then
SetDataToDatabase(lstCategory.SelectedValue.ToString)
End If
End Sub
So anything the IsLoading flag is false, the code will be allowed to run.
Hope this helps.

Related

Refreshing text in a TextBox at intervals of 1 second

I am attempting to display the local time in a text box but have it refresh... I used a timer to hopefully refresh the time, but it does not seem to reprint my text. If you could take the time to help me out that would be great!
EDIT*** So I attempted this with TextBox.AppendText() to see what happens if it continually reprints and I noticed that the date and time does not update at all. Do I need to refresh the form???
Public Class Form1
Dim t As String = My.Computer.Clock.LocalTime
Dim m As String = t & vbCrLf & " - Time Left - "
Private Timer As System.Windows.Forms.Timer
Private TimerCounter As Integer = 0
Dim TempText As String = m
Protected Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
TextBox.TextAlign = HorizontalAlignment.Center
TimerCounter += 1
TextBox.Text = t
End Sub
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Shown 'this goes with the line just above
Timer = New Windows.Forms.Timer With {.Interval = 1000}
AddHandler Timer.Tick, AddressOf TimerTick
Timer.Start()
End Sub
End Class
My expected result if for the local time to update in the textbox1 each time the timer ticks.
You set the variable t at the moment of its declaration, but then you never update it. So it contains always the same value.
In reality you don't even need that variable. You can set simply the TextBox.Text to the My.Computer.Clock.LocalTime
Protected Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
' You can set this property just one time when you define your TextBox
' TextBox.TextAlign = HorizontalAlignment.Center
TimerCounter += 1
TextBox.Text = My.Computer.Clock.LocalTime
End Sub

Shorten code vb.net

Is it possible to shorten these codes? If yes, how? Thanks for your answer guys.
Private Sub txtFirstName_GotFocus(sender As Object, e As EventArgs) Handles txtFirstName.GotFocus
lblFirstName.Visible = True
End Sub
Private Sub txtLastName_GotFocus(sender As Object, e As EventArgs) Handles txtLastName.GotFocus
lblLastName.Visible = True
End Sub
Private Sub txtMiddleName_GotFocus(sender As Object, e As EventArgs) Handles txtMiddleName.GotFocus
lblMiddleName.Visible = True
End Sub
Private Sub txtAddress_GotFocus(sender As Object, e As EventArgs) Handles txtAddress.GotFocus
lblAddress.Visible = True
End Sub
Private Sub txtContact_GotFocus(sender As Object, e As EventArgs) Handles txtContact.GotFocus
lblContact.Visible = True
End Sub
Since your labels and text boxes essentially have the same name (it's only the prefix that's different) you can:
Bind all GetFocus events to a single event handler.
Get the sender's name (sender is the control that raised the event), remove the txt prefix and replace it with lbl.
Look for a control by the new name (lbl...).
If found, make it visible.
In code it'd look like this:
Private Sub TextBoxes_GotFocus(sender As Object, e As EventArgs) Handles txtFirstName.GotFocus, txtLastName.GotFocus, txtMiddleName.GotFocus, txtAddress.GotFocus, txtContact.GotFocus
Const NamePrefix As String = "txt"
Const NewPrefix As String = "lbl"
Dim ctrl As Control = TryCast(sender, Control)
If ctrl IsNot Nothing AndAlso ctrl.Name.StartsWith(NamePrefix) Then 'Check if the sender's name starts with our prefix.
Dim NewName As String = NewPrefix & ctrl.Name.Remove(0, NamePrefix.Length) 'Remove the old prefix and replace it with the new one.
Dim Controls As Control() = Me.Controls.Find(NewName, True) 'Look for the control of our new name.
If Controls.Length > 0 Then 'Did we find one?
Controls(0).Visible = True 'Make it visible.
End If
End If
End Sub

SelectedIndexChanged event occures on every combo box whcih in on Form

I am working on VB.NET windows application.
I have added three combo-box on my form. The problem is , if I change
one-combo-box's index i.e. SelectedIndexChanged event occur for that combo box,
but same time SelectedIndexChanged event occurs of every other combo box which is present on that form.
Whats the problem, I am confused,am I missing something ?
Private Sub LoadBenNamesInComboBox()
DataLoaded = False
Dim oBenname As New BenDetails
oBenname.LoadAll()
cmbNEFTBenNames.DataSource = oBenname
cmbNEFTBenNames.DisplayMember = "NameOfBen"
cmbNEFTBenNames.ValueMember = "ID"
cmbRTGSBenNames.DataSource = oBenname
cmbRTGSBenNames.DisplayMember = "NameOfBen"
cmbRTGSBenNames.ValueMember = "ID"
cmbIMPSBen.DataSource = oBenname
cmbIMPSBen.DisplayMember = "NameOfBen"
cmbIMPSBen.ValueMember = "ID"
DataLoaded = True
End Sub
Private Sub cmbNEFTBenNames_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbNEFTBenNames.SelectedIndexChanged
End Sub
Private Sub cmbIMPSBen_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbIMPSBen.SelectedIndexChanged
End Sub
Private Sub cmbRTGSBenNames_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbRTGSBenNames.SelectedIndexChanged
End Sub
This happens because you are binding the drop down boxes back to the datasource, using the combo boxes datasource property.
When you select a value in one of the drop downs it automatically updates the others to the same value.
Instead you could set the data sources to a copy or array of the oBenName object.
e.g. if BenDetails is a LIST or something that uses the ToArray function you could do:
Private Sub LoadBenNamesInComboBox()
DataLoaded = False
Dim oBenname As New BenDetails
oBenname.LoadAll()
cmbNEFTBenNames.DataSource = oBenname.ToArray
cmbNEFTBenNames.DisplayMember = "NameOfBen"
cmbNEFTBenNames.ValueMember = "ID"
cmbRTGSBenNames.DataSource = oBenname.ToArray
cmbRTGSBenNames.DisplayMember = "NameOfBen"
cmbRTGSBenNames.ValueMember = "ID"
cmbIMPSBen.DataSource = oBenname.ToArray
cmbIMPSBen.DisplayMember = "NameOfBen"
cmbIMPSBen.ValueMember = "ID"
DataLoaded = True
End Sub

How do I create a boolean function that will determine if a group of radio buttons have all been selected and return a message box to the user?

I was given an assignment to create a program for an airline in which allows the user to select their seat. After each seat is selected, I am suppose to set the corresponding buttons array element’s Enabled property to False. Once all of the available seats are taken, I am required to create a Boolean function to check if there are any seats available. If all seats are taken, then a message box should pop up and tell the user this information.
The problem is I can't seem to get the message box to show up once all of the seats are taken. Please help me figure this out. I have attached my code below. Thanks!
Public Class Form1
Private availableSeats(7) As Boolean
Private buttons(7) As RadioButton
Private truth As Boolean
Private Sub UpdateSeatButtons()
For x As Integer = 0 To 7
If availableSeats(x) = False Then
buttons(x).Enabled = False
End If
Next
End Sub
Private Function CheckForAvailable() As Boolean
Dim seat As Boolean
For Each seat In availableSeats
If seat = True Then
truth = True
Return truth
End If
Next
truth = False
Return truth
End Function
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To 7
buttons(i) = New RadioButton
Next
buttons(0) = seat10ARadioButton
buttons(1) = seat11ARadioButton
buttons(2) = seat12ARadioButton
buttons(3) = seat13ARadioButton
buttons(4) = seat10BRadioButton
buttons(5) = seat11BRadioButton
buttons(6) = seat12BRadioButton
buttons(7) = seat13BRadioButton
For i As Integer = 0 To 7
buttons(i).Checked = False
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Caption As String = "Seat Update"
Dim boxButtons As MessageBoxButtons = MessageBoxButtons.OK
Dim Result As DialogResult
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Then
availableSeats(z) = False
Result = MessageBox.Show(Message, Caption, boxButtons)
Else
availableSeats(z) = True
End If
Next
UpdateSeatButtons()
CheckForAvailable()
If truth = False Then
MessageBox.Show("This flight is full", "No seats available", MessageBoxButtons.OK)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
End Class
Below is a set of instructions my professor gave me:
Instructions
In this case, you will create a Visual Basic solution that allows the
Island Breezes Sea Planes airline to assign seats to passengers. This
program demonstrates the use of parallel one-dimensional arrays. One
array is used to represent the availability of each seat. The other
array is used to manage the RadioButton controls on the form. It
introduces the technique of using an array of RadioButton objects.
Here are instructions on how to design and code this project:
Step 1: Create the Project: Create a Visual Basic Project using the
project name “AirplaneSeating”.
Step 2 – Design the Form: Design the form as shown in Figure 1. You
will need two button controls, one textbox, one group box, eight radio
buttons, one picture box, and two label controls.
Step 3 – Declare the form-level arrays: Declare an array of Boolean
values to indicate the availability of each seat:
Private availableSeats(7) As Boolean Declare an object array as type RadioButton:
Private buttons(7) As RadioButton
Step 3 – Add code in the Form’s Load event to initialize the arrays:
Each object in the buttons array must be initialized to be a
RadioButton object. In the Form’s Load event, write a loop to
initialize each array element using this syntax: buttons(i) = New
RadioButton
After this loop, load each individual radio button into an array
position, using this syntax (in this example, the first radio button
control’s name is seat10ARadioButton, and it is being loaded into the
first object array position):
buttons(0) = seat10ARadioButton Do this for each radio button control.
Finally, write a loop to set the Checked property of all of the
buttons array elements to False.
Step 4 – Create a sub procedure for showing seat availability on the
form: Create a sub procedure named UpdateSeatButtons that will loop
through the availableSeats array. If an element in the availableSeats
array equals False, set the corresponding buttons array element’s
Enabled property to False to visually indicate that this seat is no
longer available.
Step 5 – Create a function for determining if there are any seats
still available: Create a Boolean function named CheckForAvailable
that will loop through the c array to determine if there are any seats
still available. If there is at least one seat available, return a
True value; otherwise, return False.
Step 6 – Add code in the Confirm Seat button’s Click event to update
the seating chart: Loop through the buttons array to determine which
button was selected. Set the corresponding availableSeats array
element to False. Then call the UpdateSeatButtons sub procedure to
update the visual seating chart.
Call the CheckForAvailable function to determine whether you should
display a message indicating that the flight is full.
Step 7 – Finish up:
Be sure to add the code for the Exit button.
Step 8: Save and run Save all files, then start the application.
Test the program using various selections. Figure 2 shows a sample
run of this program, with the user’s choices shown. Notice that the
unavailable seats are grayed.
Thank you so much for all of your help! I was able to solve the problem. I have attached my final code below. Thanks again!
Public Class Form1
Private availableSeats(7) As Boolean
Private buttons(7) As RadioButton
Private truth As Boolean
Private Sub UpdateSeatButtons()
For z As Integer = 0 To 7
If availableSeats(z) = False Then
buttons(z).Enabled = False
End If
Next
End Sub
Private Function CheckForAvailable() As Boolean
Dim seat As Boolean
For Each seat In availableSeats
If seat = True Then
truth = True
Return truth
End If
Next
truth = False
Return truth
End Function
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For z As Integer = 0 To 7
buttons(z) = New RadioButton
Next
buttons(0) = seat10ARadioButton
buttons(1) = seat11ARadioButton
buttons(2) = seat12ARadioButton
buttons(3) = seat13ARadioButton
buttons(4) = seat10BRadioButton
buttons(5) = seat11BRadioButton
buttons(6) = seat12BRadioButton
buttons(7) = seat13BRadioButton
For z As Integer = 0 To 7
buttons(z).Checked = False
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Caption As String = "Seat Update"
Dim boxButtons As MessageBoxButtons = MessageBoxButtons.OK
Dim Result As DialogResult
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Then
availableSeats(z) = False
Result = MessageBox.Show(Message, Caption, boxButtons)
ElseIf buttons(z).Enabled = False Then
availableSeats(z) = False
Else
availableSeats(z) = True
End If
Next
UpdateSeatButtons()
CheckForAvailable()
If truth = False Then
MessageBox.Show("This flight is full", "No seats available", MessageBoxButtons.OK)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
End Class
In your for loop add buttons(z).Enabled = False:
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Or buttons(z).Enabled = False Then
If buttons(z).Checked Then
Result = MessageBox.Show(Message, Caption, boxButtons)
End If
availableSeats(z) = False
Else
availableSeats(z) = True
End If
Next
Every time you press the button you set the availableSeats array to true except for the checked one including of course your disabled ones.
EDIT
Initialize availableSeats to true:
For i As Integer = 0 To 7
availableSeats(i) = True
Next
and
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Then
Result = MessageBox.Show(Message, Caption, boxButtons)
availableSeats(z) = False
Exit For
End If
Next
valter
I would suggest a number of changes to your code. You do not need to create the buttons and availableSeats arrays; just use the controls themselves. This approach eliminates setting and testing for available seats. I created a new Sub that handles all RadioButton click events and disables the associated control. Let me know if I have misunderstood the requirements or need help interpreting my code.
Private Function CheckForAvailable() As Boolean
For Each ctl As Control In Controls
If TypeOf ctl Is RadioButton Then
If ctl.Enabled Then Return True ' could have tested for Checked too
End If
Next
Return False
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' no need to initialize anything here
End Sub
Private Sub SeatClicked(sender As Object, e As EventArgs) Handles RadioButton1.Click, RadioButton2.Click, RadioButton3.Click, RadioButton4.Click, RadioButton5.Click, RadioButton6.Click, RadioButton7.Click, RadioButton8.Click
If CType(sender, RadioButton).Checked Then
If CType(sender, RadioButton).Checked Then
CType(sender, RadioButton).Enabled = False
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim boxButtons As MessageBoxButtons = MessageBoxButtons.OK
If Not CheckForAvailable() Then
MessageBox.Show("This flight is full", "No seats available", MessageBoxButtons.OK)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub

Filling a TableAdapter from Bound ToolStripComboBox

I am trying to fill a TableAdapter based on a selection from a ToolStripComboBox.
First I want to fill the ToolStipComboBox by binding it to a datasource. Then once it is filled, I want to fill the TableAdapter.
This is my code:
Private Sub ToolStripComboBox_MessageType_Click(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.Click
Me.ToolStripComboBox_MessageType.ComboBox.DataSource = DataSet_UToolDb.XML_MESSAGE_TYPE
Me.ToolStripComboBox_MessageType.ComboBox.DisplayMember = "MessageType"
Me.ToolStripComboBox_MessageType.ComboBox.ValueMember = "MTId"
End Sub
Private Sub ToolStripComboBox_MessageType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.SelectedIndexChanged
Me.TableAdapter_XML_MESSAGE_STRUCTURE.Fill(DataSet_UToolDb.XML_MESSAGE_STRUCTURE, Me.ToolStripComboBox_MessageType.ComboBox.SelectedValue)
End Sub
For some reason (if I step through my code) the code jumps from the where the datasource is set, to where the TableAdapter is filled. This is causing an exception as the TableAdapter's select query is looking for a value based on the value that was selected from the ToolStipComboBox.
I suspect your code is jumping to where the TableAdapter is filled because by setting the DataSource of the ComboBox you're causing the SelectedIndexChanged event to be fired.
So, you need to tell the SelectedIndexChanged handler to return should the ToolStripComboBox not be populated yet, which you could do by setting a Boolean flag when the ToolStripComboBox has been populated. For example:
Dim m_ToolStripComboBoxPopulated As Boolean
Private Sub ToolStripComboBox_MessageType_Click(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.Click
Me.m_ToolStripComboBoxPopulated = False
Me.ToolStripComboBox_MessageType.ComboBox.DataSource = DataSet_UToolDb.XML_MESSAGE_TYPE
Me.ToolStripComboBox_MessageType.ComboBox.DisplayMember = "MessageType"
Me.ToolStripComboBox_MessageType.ComboBox.ValueMember = "MTId"
' Indicate ToolStripComboBox has been populated
Me.m_ToolStripComboBoxPopulated = True
End Sub
Private Sub ToolStripComboBox_MessageType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.SelectedIndexChanged
If (Me.m_ToolStripComboBoxPopulated = False) Then
Return
End If
Me.TableAdapter_XML_MESSAGE_STRUCTURE.Fill(DataSet_UToolDb.XML_MESSAGE_STRUCTURE, Me.ToolStripComboBox_MessageType.ComboBox.SelectedValue)
End Sub