Passing information between two forms from treeview - vb.net

I have a sub that brings a second form with a treeview on it that is populated from an array. I want to click on an item on the array and pass the key and text back to the sub and close the second form.
I feel like this should be easy but I cannot figure this out. The array is passed to the treeview as follows.
For j = 0 To NoFlowsheets - 1
Form2.TreeView1.Nodes.Add("Flowsheet" & CStr(j), ColumnNames(j, 0))
For k = 0 To j_max - 1
If ColumnNames(j, k) <> "NAME_EMPTY DO_NOT_USE_THIS_NAME" Then
Form2.TreeView1.Nodes(j).Nodes.Add("Flowsheet" & CStr(j), ColumnNames(j, k))
End If
Next k
Next j
Form2.ShowDialog()
after this a form pops up with the treeview. I want the user to click on one of the items in the tree view and pass it back to the sub

This is a very basic example, but it shows how you can pass something into a form, and how to get back what the user selected/entered. You can easily modify this to pass in your array, and pass back the selected value(s).
On the first form (where you open the child form), you add code like this:
Public Class frmStart
Private Sub btnAskUser_Click(sender As Object, e As EventArgs) Handles btnAskUser.Click
Dim frmAskUserAboutThemselves As New frmQuestion(19, "John Doe")
frmAskUserAboutThemselves.ShowDialog(Me)
If frmAskUserAboutThemselves.WasRecordSaved = True Then
lblStatus.Text = "Name: " & frmAskUserAboutThemselves.ValueThatUserSelectedOnTheFormName & vbCrLf & "Age: " & frmAskUserAboutThemselves.ValueThatUserSelectedOnTheFormAge
Else
lblStatus.Text = "The user did not enter/select any values."
End If
frmAskUserAboutThemselves.Dispose()
Beep()
End Sub
End Class
On the child form (where you ask the user to select something), you add code like this:
Public Class frmQuestion
#Region " Override Windows Form Designer Generated Code "
Public Sub New(Optional ByVal iAge As Integer = 0, Optional ByVal sName As String = "")
MyBase.New()
m_iPassedInPersonAge = iAge
m_sPassedInPersonName = sName
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
#End Region
#Region " Form Level Variables "
Private m_iPassedInPersonAge As Integer = 0
Private m_sPassedInPersonName As String = ""
Private m_bWasRecordSaved As Boolean = False
#End Region
#Region " Form Level Functions "
Public ReadOnly Property WasRecordSaved() As Boolean
Get
Return m_bWasRecordSaved
End Get
End Property
Public ReadOnly Property ValueThatUserSelectedOnTheFormName() As String
Get
Return m_sPassedInPersonName
End Get
End Property
Public ReadOnly Property ValueThatUserSelectedOnTheFormAge() As Integer
Get
Return m_iPassedInPersonAge
End Get
End Property
#End Region
#Region " Normal Page Code "
Private Sub frmQuestion_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtName.Text = m_sPassedInPersonName
NumericUpDownAge.Value = m_iPassedInPersonAge
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
m_bWasRecordSaved = False
Me.Close()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
m_iPassedInPersonAge = NumericUpDownAge.Value
m_sPassedInPersonName = txtName.Text.Trim
m_bWasRecordSaved = True
Me.Close()
End Sub
#End Region
End Class
If you are unsure what controls i placed on each form, just ask, but it should be pretty easy to figure that out.

Related

Passing data through form with showdialog but without closing event

I have a first form (form_notice_hashtag) called like this:
Public Sub afficher_hashtag(hashtag As String, plateforme_hashtag As String)
Dim form_notice_hashtag_1 As New form_notice_hashtag
form_notice_hashtag_1.StartPosition = FormStartPosition.CenterScreen
form_notice_hashtag_1.Show()
End Sub
In form_notice_hashtag_1, i have a button calling a 2nd form (form_recherche_thesaurus) like this:
Private Sub hashtag_thesaurus_search_button_Click(sender As Object, e As EventArgs) Handles hashtag_thesaurus_search_button.Click
Dim form_recherche_thesaurus_1 As New form_recherche_thesaurus With {
.StartPosition = FormStartPosition.Manual,
.Location = New Point(Me.Left + Me.Width, Me.Top)
}
form_recherche_thesaurus_1.ShowDialog(Me)
End Sub
In form_recherche_thesaurus, i have a datagridview listing some words. The user can select one word, then by clicking a button in form_recherche_thesaurus, the word which will be added to a textbox in form_notice_hashtag
Private Sub thesaurus_ok_button_Click(sender As Object, e As EventArgs) Handles thesaurus_ok_button.Click
Dim list_terms_array As String()
Select Case Owner.Name.ToString
Case "form_notice_hashtag"
list_terms_array = Split(Remove_Duplicates_From_Strings_With_SemiColon(form_notice_hashtag.hashtag_descripteurs_txtbox.Text & ";" & selected_term), ";")
form_notice_hashtag.hashtag_descripteurs_txtbox.Text = (String.Join(";", list_terms_array.Where(Function(s) Not String.IsNullOrEmpty(s))))
End Select
End Sub
I used a select because this mechanism would be used in the same way with other forms than form_notice_hashtag.
Problem: the textbox in form_notice_hashtag is not filled with the selected keywords. I guess it's because of the way form_notice_hashtag is called.
I can't use the solution as explained here Send values from one form to another form because i understood (maybe badly) that this solution works only if the 2nd form (form_recherche_thesaurus in my case) is closed (i.e closing was the trigger) which i don't want.
How can I proceed?
Thanks to jmcilhinney and this page of his blog, here is the solution that allows to transfer several data from a called form (form_recherche_thesaurus) to a calling form (form_notice_hashtag) without closing the called form .
Public Class form_notice_hashtag
Private WithEvents form_recherche_thesaurus_1 As form_recherche_thesaurus
Private selected_thesaurus_term As String
Private Sub form_recherche_thesaurus_1_TextBoxTextChanged(sender As Object, e As EventArgs) Handles form_recherche_thesaurus_1.TextBoxTextChanged
Dim list_terms_array As String() = Split(Remove_Duplicates_From_Strings_With_SemiColon(Me.hashtag_descripteurs_txtbox.Text & ";" & form_recherche_thesaurus_1.selected_term), ";")
Me.hashtag_descripteurs_txtbox.Text = (String.Join(";", list_terms_array.Where(Function(s) Not String.IsNullOrEmpty(s))))
End Sub
Private Sub hashtag_thesaurus_search_button_Click(sender As Object, e As EventArgs) Handles hashtag_thesaurus_search_button.Click
Dim form_recherche_thesaurus_1 As New form_recherche_thesaurus With {
.StartPosition = FormStartPosition.Manual,
.Location = New Point(Me.Left + Me.Width, Me.Top)
}
If Me.form_recherche_thesaurus_1 Is Nothing OrElse Me.form_recherche_thesaurus_1.IsDisposed Then
Me.form_recherche_thesaurus_1 = New form_recherche_thesaurus With {
.StartPosition = FormStartPosition.Manual,
.Location = New Point(Me.Left + Me.Width, Me.Top)
}
Me.form_recherche_thesaurus_1.Show()
End If
Me.form_recherche_thesaurus_1.Activate()
End Sub
End Class
Public Class form_recherche_thesaurus
Public Event TextBoxTextChanged As EventHandler
Private term_thesaurus As String
Public Property selected_term() As String
Get
Return term_thesaurus
End Get
Set(ByVal value As String)
term_thesaurus = value
End Set
End Property
Private Sub thesaurus_ok_button_Click(sender As Object, e As EventArgs) Handles thesaurus_ok_button.Click
Dim list_terms_array As String()
Me.selected_term = Me.thesaurus_search_results_datagrid.Item(0, Me.thesaurus_search_results_datagrid.CurrentRow.Index).Value
Me.DialogResult = DialogResult.OK
RaiseEvent TextBoxTextChanged(Me, EventArgs.Empty)
End Sub

Add array values from textboxes and display in a label

enter image description here <<< my interface
I am working on something for my exam next week.
I must use Visual Basic. I am supposed to create an array with an integer and string. Integer = distance String = name. there will be 2 textboxes, 2 labels and 2 buttons.
txtname.text, txtdistance.text, lblname, lbldistance, btninputdata and btnshowcontent
btninputdata should be disabled after filling the 30 arrays and making btnshowcontent to be visible and show all the 30 values (inserted values via textboxes) in lblname and lbldistance.
Whereas they both need to be inserted via a textbox store into the array and then using a btnshowcontent the stored array should be displayed on separate labels of name and distance.
My codes:
Public Class Form1
Dim ara(29) As String
Private Sub Form1_Load(sender As Object, e As EventArgs)
End Sub
Private Sub btninputdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninputdata.Click
If txtname.Text <> "" Then
For h As Integer = 0 To 29
If ara(h) = "" Then
ara(h) = txtname.Text
txtname.Clear()
Exit Sub
End If
Label1.Text = ara.ToString()
Next
MsgBox("arry full")
btninputdata.Visible = False
btnshowcontent.Visible = True
End If
End Sub
Private Sub btnshowcontent_Click(sender As Object, e As EventArgs) Handles btnshowcontent.Click
'ListBox1.Items.Clear()
'ListBox1.Items.AddRange(ara)
''Label1.Text &= ara(I) & ""
End Sub
Private Sub Form1_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
You'll want to start with something like this. Not sure how you're really trying to display everything, though. You'd probably want to do validation on the distance field also.
Public Class Form1
Dim Ara As New List(Of MyGroup)
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Ara.Add(New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text})
If Ara.Count >= 30 Then
'Show/Hide buttons
End If
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class
If you truly must use an array you can do something like this:
Public Class Form1
Private Ara(29) As MyGroup
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Dim EmptyLocation = Array.FindIndex(Ara, Function(x) x Is Nothing)
If EmptyLocation > -1 Then
Ara(EmptyLocation) = New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text}
Return
End If
'Show/Hide buttons
'Display the results however.
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class

Why is it only displaying one result

This program is supposed to accept in valid candidates for voting, add the names typed in a text box to a list box. In the list box the user may double click on the candidate they choose. After the tally button is clicked a list box displaying the candidates' Names and votes will appear along side the other list box.
My problem is that the lstTallies only displays the last voted candidate.
Below is my code
Public Class Form1
Dim maxVotes As Integer
Dim winner As String
Dim votes() As Integer
Dim index As Integer
Dim candidates As String
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If Not isValidInput(txtNewCandidate.Text) Then
Exit Sub
End If
lstCandidates.Items.Add(txtNewCandidate.Text)
txtNewCandidate.Clear()
txtNewCandidate.Focus()
ReDim Preserve votes(index)
index += 1
End Sub
Private Function isValidInput(ByRef firstName As String) As Boolean
If IsNumeric(txtNewCandidate.Text) Or txtNewCandidate.Text = "" Then
MsgBox("Please input a valid candidate name.")
txtNewCandidate.Focus()
Return False
Else
Return True
End If
End Function
Private Sub btnTally_Click(sender As Object, e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
lstTallies.Items.Add(lstCandidates.Text & " " & votes(lstCandidates.SelectedIndex))
End Sub
Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
If lstCandidates.SelectedIndex = -1 Then
MsgBox("Select a candidate by double-clicking")
End If
votes(lstCandidates.SelectedIndex) += 1
MsgBox("Vote Tallied")
End Sub
End Class
Try this:
Assuming the index of the Candidate and his/her Vote are the same:
Private Sub btnTally_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
For i = 0 To lstCandidates.Items.Count - 1
lstTallies.Items.Add(lstCandidates.Items(i).ToString & " - " & votes(i))
Next
End Sub
You cannot get the contents of the ListBox unless you iterate it.

How do you change the value in my.settings in a form when you enter numbers in a textbox in VB.Net

I was wondering if you could help me? My question is that, is there a way of changing the value in my.Settings in a form if you enter a number/decimal in a textbox and click a button and then update in the settings to be then changed in another from which is linked to my.Settings in a variable?!
Form 1:
Public Class frmConverter
Dim input As String
Dim result As Decimal
Dim EUR_Rate As Decimal = My.Settings.EUR_Rates
Dim USD_Rate As Decimal = 1.6
Dim JYP_Rate As Decimal = 179.65
Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
input = txtInput.Text
Try
If ComboBox1.Text = "£" Then
Pounds()
ElseIf ComboBox1.Text = "€" Then
Euros()
ElseIf ComboBox1.Text = "$" Then
Dollars()
ElseIf ComboBox1.Text = "¥" Then
Yen()
End If
Catch es As Exception
MsgBox("Error!")
End Try
End Sub
Private Sub btnSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettings.Click
Me.Hide()
frmExchange.Show()
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
txtInput.Text = ""
lblResult.Text = ""
End Sub
Function Pounds()
If ComboBox1.Text = "£" And ComboBox2.Text = "€" Then
result = (input * EUR_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "$" Then
result = (input * USD_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "¥" Then
result = (input * JYP_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
End If
Return 0
End Function
Form 2:
Public Class frmExchange
Private Sub frmExchange_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
My.Settings.EUR_Rates = (txtinput.Text)
My.Settings.Save()
My.Settings.Reload()
End Sub
Public Sub SetNewRate(ByVal rate As Decimal)
txtinput.Text = rate.ToString
End Sub
Private Sub btnchange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnchange.Click
If ComboBox1.Text = "€" Then
My.Settings.USD_Rates = (txtinput.Text)
frmConverter.SetNewRate(txtinput.Text)
End If
End Sub
End class
It sounds like you are trying to use My.Settings as some sort of set of global reference variables. Thats not what they are for, not how they work and not what they are.
First, turn on Option Strict as it looks like it may be Off. This will store the decimal value of a textbox to a Settings variable which is defined as a Decimal:
My.Settings.USD_Rates = CDec(SomeTextBox.Text)
Thats all it will do. It wont save the value and it wont pass it around or share it with other forms and variables.
My.Settings.Save 'saves current settings to disk for next time
My.Settings.Reload 'Load settings from last time
This is all covered on MSDN. There is no linkage anywhere. If you have code in another form like this:
txtRate.Text = My.Settings.USD_Rates.ToString
txtRate will not automatically update when you post a new value to Settings. There are just values not Objects (see Value Types and Reference Types). To pass the new value to another form:
' in other form:
Public Sub SetNewRate(rate As Decimal)
' use the new value:
soemTextBox.Text = rate.ToString
End Sub
in form which gets the change:
Private Sub btnchangeRate(....
' save to settings which has nothing to do with passing the data
My.Settings.USD_Rates = CDec(RateTextBox.Text)
otherForm.SetNewRate(CDec(RateTextBox.Text))
End Sub
You may run into problems if you are using the default form instance, but that is a different problem.
You botched the instructions. The 2 procedures are supposed to go in 2 different forms - one to SEND the new value, one to RECEIVE the new value. With the edit and more complete picture, there is an easier way.
Private Sub btnSettings_Click(...) Handles btnSettings.Click
' rather than EMULATE a dialog, lets DO a dialog:
'Me.Hide()
'frmExchange.Show()
Using frm As New frmExchange ' the proper way to use a form
frm.ShowDialog
' Im guessing 'result' is the xchg rate var
result = CDec(frm.txtInput.Text)
End Using ' dispose of form, release resources
End Sub
In the other form
Private Sub btnchange_Click(....)
' do the normal stuff with Settings, if needed then:
Me.Hide
End Sub

ComboBox.SelectedValue getting reset in Windows XP only

I'm having some issues with WinForms ComboBox class. What I am trying to achieve is programmatically setting SelectedValue from the ComboBox.TextChanged handler once a match is found. This works fine on Windows 7, but in Windows XP SelectedValue will get set and SelectedValueChanged will be raised, but then once it reaches Validating SelectedValue returns Nothing. It seems the only way to change SelectedValue in XP is via selecting something from the dropdown.
Here's a toy Form with just a ComboBox and a multi-line TextBox.
XP: Typed into the ComboBox is 1Y, then tab is pressed. Output:
SelectedValueChanged: SelectedValue: 1X
Validating: SelectedValue: Nothing
Value is:
Validated: SelectedValue: Nothing
Win7: Typed into the ComboBox is 1Y, then tab is pressed. Output:
SelectedValueChanged: SelectedValue: 1X
Validating: SelectedValue: 1X
Value is: 1X
Validated: SelectedValue: 1X
Code:
Public Class ComboBoxXPForm
Private WithEvents mData As New DataHolder
Private mBindingSrc As BindingSource
Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
mBindingSrc = New BindingSource() With {.DataSource = mData}
Dim dt As New DataTable()
dt.Columns.Add("value", GetType(String))
dt.Columns.Add("displayValue", GetType(String))
dt.Rows.Add("", "")
For i = 1 To 10
dt.Rows.Add(i & "X", i & "Y")
Next
cboBox.DataSource = dt
cboBox.ValueMember = "value"
cboBox.DisplayMember = "displayValue"
cboBox.DataBindings.Add("SelectedValue", mBindingSrc, "StrVal", True)
End Sub
Private Sub cboBox_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboBox.SelectedValueChanged
txtDebug.Text &= vbNewLine & "SelectedValueChanged: SelectedValue: " & _
If(cboBox.SelectedValue Is Nothing, _
"Nothing", cboBox.SelectedValue.ToString())
End Sub
Private Sub DataHolder_DebugInfo(ByVal sender As Object, ByVal e As DebugEventArgs) Handles mData.DebugInfo
txtDebug.Text &= vbNewLine & e.DebugInfo
End Sub
Private Sub cboBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboBox.TextChanged
'For Each row In cboBox.Items
' If cboBox.Text = row("displayValue") AndAlso row("value") <> cboBox.SelectedValue Then
' 'cboBox.SelectedValue = row("value")
' cboBox.SelectedItem = row
' End If
'Next
For i = 0 To cboBox.Items.Count - 1
Dim item = cboBox.Items(i)
If cboBox.Text = item("displayValue") Then
cboBox.SelectedIndex = i
End If
Next
End Sub
Private Sub cboBox_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboBox.Validated
txtDebug.Text &= vbNewLine & "Validated: SelectedValue: " & _
If(cboBox.SelectedValue Is Nothing, _
"Nothing", cboBox.SelectedValue.ToString())
End Sub
Private Sub cboBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cboBox.Validating
txtDebug.Text &= vbNewLine & "Validating: SelectedValue: " & _
If(cboBox.SelectedValue Is Nothing, _
"Nothing", cboBox.SelectedValue.ToString())
End Sub
End Class
Public Class DebugEventArgs
Inherits EventArgs
Private mDebugInfo As String
Public Sub New(ByVal DebugString As String)
MyBase.New()
DebugInfo = DebugString
End Sub
Public Property DebugInfo() As String
Get
Return mDebugInfo
End Get
Set(ByVal value As String)
mDebugInfo = value
End Set
End Property
End Class
Public Class DataHolder
Public Event DebugInfo(ByVal sender As Object, ByVal e As DebugEventArgs)
Private mStrVal As String
Public Property StrVal() As String
Get
Return mStrVal
End Get
Set(ByVal value As String)
mStrVal = value
RaiseEvent DebugInfo(Me, New DebugEventArgs("Value is: " & value))
End Set
End Property
End Class
Try turning AutoCompleteMode to become SuggestAppend, and AutoCompleteSource to become ListItems. Then you can remove the entire TextChanged code block and it should also work properly on XP.