Object returns null when it is not - vb.net

I basically i have two forms, one named 'frmSettings' and another names 'frmXLExternalFile', 'frmXLExternalFile' is created from 'frmSettings', there is data passed between these two forms and when i return it using a property it returns as null. Ive tried returning it by settings it to public but that still doesnt seem to work some strange reason. I've set breakpoints and traced the variable ( actually a structure ) and it is certainly not 'null'
frmXLExternalFile
Dim XL_File As frmMain.XLSheetData
Public ReadOnly Property XLFile As frmMain.XLSheetData
Get
Return XL_File
End Get
End Property
Private Sub frmXLExternalFile_formClosing(sender As Object, e As EventArgs) Handles MyBase.FormClosing
If txtFilepath.Text <> "" And cmboName.Text <> "" Then
XL_File = New frmMain.XLSheetData
XL_File.name = cmboName.Text
XL_File.filePath = txtFilepath.Text
frmMain.settings.setXLFile()
frmMain.settings.cmboXLSheets.Text = txtFilepath.Text
End If
frmMain.settings.Enabled = True
End Sub
frmMain (This is where the structure is declared)
Public Structure XLSheetData
Dim name As String
Dim filePath As String
End Structure
frmSettings
Dim XL_FileList As List(Of frmMain.XLSheetData)
Sub setXLFile()
Dim file As frmMain.XLSheetData = frmXLExternalFile.XLFile
XL_FileList.Add(file)
cmboXLSheets.Items.Add(file.filePath)
End Sub
basically, The top form calls this the bottom method once the field - XL_File - is filled, this then uses the property - 'XLFile' - to 'Get' the object and put it in the 'frmSettings' class. As I have said, i have tried setting 'XL_File' to public and tried accessing it directly but the same exception is thrown. It is null, the combo box and text box that are used to fill the object are not null. Any help would be appreciated. Thanks.

Here's one way to do it with Show(), by passing in the "Owner" form:
In frmSettings:
Dim frmX As New frmXLExternalFile
' ... pass some data to frmX ...
frmX.Show(Me) ' <-- pass this form in as the "Owner"
In frmXLExternalFile:
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtFilepath.Text <> "" And cmboName.Text <> "" Then
XL_File = New frmMain.XLSheetData
XL_File.name = cmboName.Text
XL_File.filePath = txtFilepath.Text
Dim main As frmSettings = DirectCast(Me.Owner, frmSettings) ' <-- use the instance passed in as the owner via Show()
' ... use "main" somehow ...
main.settings.setXLFile()
main.settings.cmboXLSheets.Text = txtFilepath.Text
main.settings.Enabled = True
Else
' ... possibly do something else ...
End If
End Sub
This example demonstrates a ShowDialog() approach:
In frmSettings:
Dim frmX As New frmXLExternalFile
' ... pass some data to frmX ...
If frmX.ShowDialog() = Windows.Forms.DialogResult.OK Then ' <-- execution in this Form STOPS until "frmX" is dismissed
' Retrieve the value from out "frmX" instance:
Dim file As frmMain.XLSheetData = frmX.XLFile
' ... do something with "file" ...
XL_FileList.Add(file)
cmboXLSheets.Items.Add(file.filePath)
cmboXLSheets.Text = file.filePath
End If
In frmXLExternalFile:
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtFilepath.Text <> "" And cmboName.Text <> "" Then
XL_File = New frmMain.XLSheetData
XL_File.name = cmboName.Text
XL_File.filePath = txtFilepath.Text
' Set DialogResult, returning execution to the ShowDialog() line:
Me.DialogResult = Windows.Forms.DialogResult.OK
Else
' ... possibly do something else ...
End If
End Sub

Related

How to save checkbox value in xml using vb.net

I know, maybe this is a question that comes up quite often, but I haven't been able to work on it.
How can I save this checkbox values in an XML file using VB.Net ?
Private Sub ChkVul_Click(sender As Object, e As EventArgs) Handles ChkVul.Click
If ChkVul.Checked = True Then
Me.pnlInsert.Visible = True
Else
Me.pnlInsert.Visible = False
End If
End Sub
Before I provide you with an answer, I wanted to recommend a slight code change. Since you are setting the Boolean value of pnlInsert.Visible based on a condition, which itself returns a Boolean value, simply get rid of the conditional check in the first place:
pnlInsert.Visible = ChkVul.Checked
Now to your question. What you are essentially asking is how to write a value to an XML file. Something to consider is that XML is only a markup language. At the end of the day, an XML file is simply a file that contains formatted text.
If you do not already have an XML file to read from, simply create a new instance of a XDocument (documentation). If you do have an XML file, then create a new instance of a XDocument by calling the static XDocument.Load method (documentation). Here is a function that takes in a file location and attempts to load a XDocument, if it is unable to then it returns a blank XDocument with a single <root> element:
Private Function LoadOrCreateXml(filename As String) As XDocument
Dim document = New XDocument()
document.Add(New XElement("root"))
Try
If (Not String.IsNullOrWhiteSpace(filename) AndAlso IO.File.Exists(filename)) Then
document = XDocument.Load(filename)
End If
Catch ex As Exception
' for the sake of this example, just silently fail
End Try
Return document
End Function
Now that you have an XDocument, it is just a matter of writing the value. You did not provide any details as to where the value should go or what the tag name should be, so I am going to assume that it should be a child of the <root /> element and the value would look something like this: <ChkVul>true/false</ChkVul>.
To do this, we will need to get the <root /> element by calling the Element method (documentation) on the XDocument to get the element and then call the Add method (documentation) on the resulting XElement to add our node with the value:
Dim document = LoadOrCreateXml("my-xml-file.txt")
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))
The final piece of all this is to write the in-memory XDocument back to the file. You can leverage the XDocument.Save method (documentation):
Dim filename = "my-xml-file.txt"
Dim document = LoadOrCreateXml(filename)
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))
document.Save(filename)
Maybe this is what you have in mind. I tested this with other controls,
Public Class Form1
Private SavePath As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"MyControls.xml") 'some valid path <-----------<<<
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
SaveCheckedState(ChkVul, "ChkVul", True)
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
If IO.File.Exists(SavePath) Then
Try
MyControls = XElement.Load(SavePath)
For Each el As XElement In MyControls.Elements
Dim ctrl() As Control = Me.Controls.Find(el.#name, True)
If ctrl.Length > 0 Then
Dim chkd As System.Reflection.PropertyInfo = ctrl(0).GetType().GetProperty("Checked")
Dim chkdV As Boolean = Boolean.Parse(el.#checked)
chkd.SetValue(ctrl(0), chkdV)
End If
Next
Catch ex As Exception
'todo
End Try
End If
End Sub
Private Sub ChkVul_CheckedChanged(sender As Object, e As EventArgs) Handles ChkVul.CheckedChanged
If ChkVul.Checked Then
Me.pnlInsert.Visible = True
Else
Me.pnlInsert.Visible = False
End If
SaveCheckedState(ChkVul, "ChkVul")
End Sub
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
SaveCheckedState(RadioButton1, "RadioButton1")
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
SaveCheckedState(CheckBox1, "CheckBox1")
End Sub
Private MyControls As XElement = <controls>
</controls>
Private Sub SaveCheckedState(Ctrl As Control,
Name As String,
Optional Save As Boolean = False)
If Ctrl.GetType().GetProperty("Checked") IsNot Nothing Then
Dim chkd As System.Reflection.PropertyInfo = Ctrl.GetType().GetProperty("Checked")
Dim chkdV As Boolean = CBool(chkd.GetValue(Ctrl))
Dim ie As IEnumerable(Of XElement)
ie = From el In MyControls.Elements
Where el.#name = Ctrl.Name
Select el Take 1
Dim thisXML As XElement
If ie.Count = 0 Then
thisXML = <ctrl name=<%= Name %>></ctrl>
MyControls.Add(thisXML)
Else
thisXML = ie(0)
End If
thisXML.#checked = chkdV.ToString
End If
If Save Then
Try
MyControls.Save(SavePath)
Catch ex As Exception
'todo
' Stop
End Try
End If
End Sub
End Class

vb.NET You are not allowed to perform an operation across different threads

I am running code to read text from pdf files and than create a WordCloud. To inform the user the process is on going I add a BackgroundWorker to my form that shows an image saying Loading. I get an error for operating across different threads.
Private Sub ButtonCreate_Click(sender As Object, e As EventArgs) Handles ButtonCreate.Click
bTextEmpty = False
ListView1.Items.Clear()
ResultPictureBox.Image = Nothing
If ListBox1.SelectedIndex > -1 Then
For Each Item As Object In ListBox1.SelectedItems
Dim ItemSelected = CType(Item("Path"), String)
Dim myTempFile As Boolean = File.Exists(ItemSelected + "\Words.txt")
If myTempFile = False Then
'when we load the form we first call the code to count words in all files in a directory
'lets check if the folder exists
If (Not System.IO.Directory.Exists(ItemSelected)) Then
Dim unused = MsgBox("The archive " + ItemSelected.Substring(ItemSelected.Length - 5, Length) + " was not found",, Title)
Exit Sub
Else
Call CreateWordList(ItemSelected)
End If
End If
'if the words file is empty we cant create a cloud so exit the sub
If bTextEmpty = True Then Exit Sub
'then we fill the wordcloud and Listview from the created textfile
Call CreateMyCloud(ItemSelected + "\Words.txt")
Next
Else
Dim unused = MsgBox("You have to choose an Archive to create the Word Cloud",, Title)
End If
Size = New Drawing.Size(1400, 800)
End Sub
I put above code in a Private Sub and called it from my BackgroundWorker. The error occured at this line: If ListBox1.SelectedIndex > -1 Then
After trying the suggested code I get the same error again:
Public Sub CreateMyCloud(ByVal sourcePDF As String)
Dim WordsFreqList As New List(Of WordsFrequencies)
For Each line As String In File.ReadLines(sourcePDF)
Dim splitText As String() = line.Split(","c)
If splitText IsNot Nothing AndAlso splitText.Length = 2 Then
Dim wordFrq As New WordsFrequencies
Dim freq As Integer
wordFrq.Word = splitText(0)
wordFrq.Frequency = If(Integer.TryParse(splitText(1), freq), freq, 0)
WordsFreqList.Add(wordFrq)
End If
Next
If WordsFreqList.Count > 0 Then
' Order the list based on the Frequency
WordsFreqList = WordsFreqList.OrderByDescending(Function(w) w.Frequency).ToList
' Add the sorted items to the listview
WordsFreqList.ForEach(Sub(wf)
error -> ListView1.Items.Add(New ListViewItem(New String() {wf.Word, wf.Frequency.ToString}, 0))
End Sub)
End If
Dim wc As WordCloudGen = New WordCloudGen(600, 400)
Dim i As Image = wc.Draw(WordsFreqList.Select(Function(wf) wf.Word).ToList, WordsFreqList.Select(Function(wf) wf.Frequency).ToList)
ResultPictureBox.Image = i
End Sub
Should look something more like:
Private Sub ButtonCreate_Click(sender As Object, e As EventArgs) Handles ButtonCreate.Click
If ListBox1.SelectedItems.Count > 0 Then
Dim data As New List(Of Object)
For Each Item As Object In ListBox1.SelectedItems
data.Add(Item)
Next
bTextEmpty = False
ListView1.Items.Clear()
ResultPictureBox.Image = Nothing
BackgroundWorker1.RunWorkerAsync(data)
Else
MessageBox.Show("You have to choose an Archive to create the Word Cloud",, Title)
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim data As List(Of Object) = DirectCast(e.Argument, List(Of Object))
For Each Item As Object In data
Dim ItemSelected = CType(Item("Path"), String)
Dim myTempFile As Boolean = File.Exists(ItemSelected + "\Words.txt")
If myTempFile = False Then
'when we load the form we first call the code to count words in all files in a directory
'lets check if the folder exists
If (Not System.IO.Directory.Exists(ItemSelected)) Then
MessageBox.Show("The archive " + ItemSelected.Substring(ItemSelected.Length - 5, Length) + " was not found",, Title)
Exit Sub
Else
Call CreateWordList(ItemSelected)
End If
End If
'if the words file is empty we cant create a cloud so exit the sub
If bTextEmpty = True Then Exit Sub
'then we fill the wordcloud and Listview from the created textfile
Call CreateMyCloud(ItemSelected + "\Words.txt")
Next
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Size = New Drawing.Size(1400, 800)
End Sub
To fix the error in your second, edited post:
WordsFreqList.ForEach(Sub(wf)
ListView1.Invoke(Sub()
ListView1.Items.Add(New ListViewItem(New String() {wf.Word, wf.Frequency.ToString}, 0))
End Sub)
End Sub)
You cannot simply access controls outside of the current thread. You first need to call the Invoke method on the target control and then pass a delegate containing the instructions intended to modify the control outside of the current thread. See this article on MSDN on how to do this: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls?view=netframeworkdesktop-4.8

vb.net combobox to return value of another column

I have two comboboxes. The second one is dependant on the first. I then pass the selected values to a second form as objects. My code works perfectly up to here. But I also need to pass a third object to the second form (i.e. plaasnopass) based on the selection of the second combobox (i.e cmbPlaasnaam). This value however is in another column. My code below runs without errors , but the third value is not passed to the second form.
Public Class ParskaartjieKiesFrm
Dim obj As New Parskaartjies
Private Sub ParskaartjieKiesFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'SkeduleringDatabasisDataSet.wingrd13' table. You can move, or remove it, as needed.
Me.Wingrd13TableAdapter.Fill(Me.SkeduleringDatabasisDataSet.wingrd13)
With CmbAliasnaam
.BeginUpdate()
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
Dim qry = From zc As SkeduleringDatabasisDataSet.wingrd13Row In SkeduleringDatabasisDataSet.wingrd13 _
Select zc.Aliasnaam Distinct Order By Aliasnaam
For Each ALIASNAAM As String In qry
.Items.Add(ALIASNAAM)
Next
.EndUpdate()
End With
With CmbPlaasnaam
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
.Enabled = False
End With
End Sub
Private Sub CmbAliasnaam_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbAliasnaam.SelectedIndexChanged
obj.aliasnaampass = CmbAliasnaam.SelectedItem
With CmbPlaasnaam
.SelectedIndex = -1
.Items.Clear()
.Enabled = False
End With
If CmbAliasnaam.SelectedIndex > -1 Then
CmbPlaasnaam.BeginUpdate()
Dim Aliasnaam As String = CmbAliasnaam.Items(CmbAliasnaam.SelectedIndex).ToString
Dim qry = From zc As SkeduleringDatabasisDataSet.wingrd13Row In SkeduleringDatabasisDataSet.wingrd13 _
Where zc.Aliasnaam = ALIASNAAM Select zc.Plaasnaam Distinct _
Order By Plaasnaam
For Each plaasnaam As String In qry
CmbPlaasnaam.Items.Add(plaasnaam)
Next
If CmbPlaasnaam.Items.Count > 0 Then
CmbPlaasnaam.Enabled = True
End If
CmbPlaasnaam.EndUpdate()
End If
End Sub
Private Sub CmbPlaasnaam_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbPlaasnaam.SelectedIndexChanged
obj.plaasnaampass = CmbPlaasnaam.SelectedItem
obj.plaasnopass = CmbAliasnaam.SelectedValue
obj.Show()
Me.Close()
End Sub
End Class
How do I go about ?
Regards
According to your comment, I understood that you have combo box loaded from
select a from t
but this gives you single value, and you want to load
select a, b from t
and pass both values to next form.
It is helpful that you're using LINQ!! Modify it. But first declare new type
Public Class CboItem
Public Property Display As String
Public Property Value As String ' <-- any datatype
' .... any number of properties here
End Class
Dim qry =
(From zc As SkeduleringDatabasisDataSet.wingrd13Row
In SkeduleringDatabasisDataSet.wingrd13 _
Where zc.Aliasnaam = ALIASNAAM
Select New CboItem() With { .Display = zc.Plaasnaam, .Value = zs.[...] }).
Distinct(function(item)...).OrderBy(function(item)...)
CmbAliasnaam.DisplayMember = "Display"
CmbAliasnaam.ValueMember = "Value"
CmbAliasnaam.DataSource = qry.ToList()
Now you can pass to your form selected item or whatever you get out of it. for example
Dim item As CboItem = TryCast(CmbAliasnaam.SelectedItem, CboItem)
If item IsNot Nothing Then
frm.SetSelected(item.Display, item.Value, item.anyOtherProperty)
End If
' or
frm.SomeProperty = item
As you see, you can pass an object that you can store in combo box. It doesn't have to be string.

Importing a CSV into a combobox, then changing other things in VB

What I want to do is import a CSV file (called fwlist.txt), that looks like this:
modelname,power type,pic,part number,firmware, option1, option 1, etc
End result, i would like a combobox that shows the modelname, and when the model name is selected from the pulldown, it updates various labels and text boxes on the form with other information.
Here's what I have so far:
Dim filename As String = "fwlist.txt"
Dim pwrtype As String
Dim pic As String
Dim partnum As String
Dim lineread As String
Dim FirmwareName As String
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
FirmwareName = fields(0) 'Take First Field
cbFW.Items.Add(FirmwareName)
'Set Text labels based on position in line.
pwrtype = fields(1)
pic = fields(2)
partnum = fields(3)
(...etc through options)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
lblPwrType.Text = pwrtype
lblPic.Text = pic
lblPartNum.Text = parnum
....etc thruogh options
End Sub
This code works, but only sort of. If i select anything from the combo box, it only gives me the information from the very last line of the CSV file - even if its the first entry in the box. I'm pretty sure it's something simple that I'm messing up.. anyone help?
First we read the lines into Firmware objects then we set this List(Of Firmware) as the DataSource of the ComboBox.
Then we handle the SelectedIndexChanged event of the ComboBox which will get the currently selected firmware and loads its data to the TextBox controls.
This is a tested, working example below:
Public Class Firmware
Public Property ModelName As String
Public Property PowerType As String
Public Property Pic As String
Public Property PartNumber As String
Public Property Firmware As String
Public Property Option1 As String
End Class
Public Class MainForm
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines As String() = Nothing
Try
' Read the file in one step
lines = File.ReadAllLines("fwlist.txt")
Catch ex As Exception
Dim dialogResult As DialogResult = MessageBox.Show(Me, "File not found! Would you like to exit program?", "Error reading file", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2)
If dialogResult = DialogResult.Yes Then
Me.Close()
End If
Exit Sub
End Try
Dim firmwares As List(Of Firmware) = New List(Of Firmware)
For Each line As String In lines
Dim rawData As String() = line.Split({","}, StringSplitOptions.None)
' Create Firmware object from each line
Dim firmware As Firmware = New Firmware() With
{
.ModelName = rawData(0),
.PowerType = rawData(1),
.Pic = rawData(2),
.PartNumber = rawData(3),
.Firmware = rawData(4),
.Option1 = rawData(5)
}
' We store the read firmwares into a list
firmwares.Add(firmware)
Next
' Set the list as the data source of the combobox
' DisplayMember indicates which property will be shown in the combobox
With cboModelNames
.DataSource = firmwares
.DisplayMember = "ModelName"
End With
End Sub
Private Sub cboModelNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelNames.SelectedIndexChanged
RefreshForm()
End Sub
Private Sub RefreshForm()
' Get the selected item as Firmware object
Dim currentFirmware As Firmware = DirectCast(cboModelNames.SelectedItem, Firmware)
' Refresh all the textboxes with the information
With currentFirmware
txtPowerType.Text = .PowerType
txtPic.Text = .Pic
txtPartNumber.Text = .PartNumber
txtFirmware.Text = .Firmware
txtOption1.Text = .Option1
End With
End Sub
End Class
Every time you set the value of a variable like pwrtype, its old value is thrown away and there is no way to get it back. And even if you did save multiple values for each variable, you would need a way to figure out which value goes with the currently selected item in the combo box. To resolve these two issues you need:
a way to group values from the same line together
a way to save all values read from the file, not just the most recent ones
Let's start with the first issue, grouping values together. In the example code below, I created a Structure type called FirmwareInfo to serve that purpose. Each FirmwareInfo has its own pwrtype, pic, etc.
The other piece of the puzzle that you are missing is a way to save more than one Firmware. The easiest way to do this is to add each FirmwareInfo to the combo box's item list, instead of adding just the display string. The combo box will convert each item to a string in the UI; the ToString() method tells it how you want this conversion to be done.
I haven't run this example code so I can't guarantee there aren't mistakes in there, but hopefully it's enough to show the general idea.
Dim filename As String = "fwlist.txt"
Structure FirmwareInfo
Public pwrtype As String
Public pic As String
Public partnum As String
Public FirmwareName As String
Public Overrides Function ToString() As String
Return FirmwareName
End Function
End Structure
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
Dim lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
Dim info As New FirmwareInfo With {
.FirmwareName = fields(0),
.pwrtype = fields(1),
.pic = fields(2),
.partnum = fields(3)
}
cbFW.Items.Add(info)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
Dim currentInfo = DirectCast(cbFW.SelectedItem, FirmwareInfo)
lblPwrType.Text = currentInfo.pwrtype
lblPic.Text = currentInfo.pic
lblPartNum.Text = currentInfo.parnum
' ....etc through options
End Sub

vb.net Find Form

In the Windows, the native Notepad program has a find form. Basically When the user types and hits 'Find Next', the program proceeds to find the text while keeping the focus on the Find form. This way the user can keep hitting the 'Enter' key or the button and still have the text highlighted while the form is focused.
My problem is that I have a different form for the "Search" feature and whenever the user hits "Enter" the text is found and the focus is set on the TextBox but when the user hits "Enter" again, the text gets edited because of the focus.
Currently, I'm using Regex to do this and I am using a WPF TextBox using HostElement:
Private Function GetRegExpression() As Regex
Dim result As Regex
Dim regExString As [String]
regExString = txtbx_Find.Text
If matchCaseCheckBox.Checked Then
result = New Regex(regExString)
Else
result = New Regex(regExString, RegexOptions.IgnoreCase)
End If
Return result
End Function
Private Sub FindText()
''
Dim WpfTest1 As New SpellPad.Tb
Dim ElementHost1 As System.Windows.Forms.Integration.ElementHost = frm_Menu.Controls("ElementHost1")
Dim TheTextBox As System.Windows.Controls.TextBox = CType(ElementHost1.Child, Tb).ctrl_TextBox
''
If isFirstFind Then
regex = GetRegExpression()
match = regex.Match(TheTextBox.Text)
isFirstFind = False
Else
match = regex.Match(TheTextBox.Text, match.Index + 1)
End If
If match.Success Then
Dim row As Integer = TheTextBox.GetLineIndexFromCharacterIndex(TheTextBox.CaretIndex)
MoveCaretToLine(TheTextBox, row + 1)
TheTextBox.SelectionStart = match.Index
TheTextBox.SelectionLength = match.Length
TheTextBox.Focus()
Me.Focus()
Else
MessageBox.Show([String].Format("Cannot find ""{0}"" ", txtbx_Find.Text), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
isFirstFind = True
End If
End Sub
Private Sub btn_FindNext_Click(sender As Object, e As EventArgs) Handles btn_FindNext.Click
''
Dim WpfTest1 As New SpellPad.Tb
Dim ElementHost1 As System.Windows.Forms.Integration.ElementHost = frm_Menu.Controls("ElementHost1")
Dim TheTextBox As System.Windows.Controls.TextBox = CType(ElementHost1.Child, Tb).ctrl_TextBox
''
FindText()
'theTextBox.Focus()
End Sub
I want it to be just like Notepad where the user hits "Enter" and keeps focus on the Find Form while selecting the text. How can this be achieved?
I think you should catch "keyup" event of your form like this :
Class MainWindow
Private Sub Window_KeyUp(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles MyBase.KeyUp
If e.Key = Key.Enter Then
FindNext()
End If
End Sub
Private Sub btn_FindNext_Click(sender As Object, e As EventArgs) Handles btn_FindNext.Click
FindText()
End Sub
Private Sub FindNext()
''
Dim WpfTest1 As New SpellPad.Tb
Dim ElementHost1 As System.Windows.Forms.Integration.ElementHost = frm_Menu.Controls("ElementHost1")
Dim TheTextBox As System.Windows.Controls.TextBox = CType(ElementHost1.Child, Tb).ctrl_TextBox
''
FindText()
'theTextBox.Focus()
End Sub
End Class