How do you change the value in my.settings in a form when you enter numbers in a textbox in VB.Net - 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

Related

Passing information between two forms from treeview

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.

call sub to change USERname color

I want to change USERname color inside RitchTextBox, I am using this code below to call the SUB but all the text now in red?
UPDATE
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & "$ ")
box.SelectionColor = Color.Black
box.AppendText(txtSend)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click
' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text)
Try
If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then
MsgBox("wright a message!", "MsgBox")
Else
client = New TcpClient(txtPCIPadd.Text, 44444)
Dim writer As New StreamWriter(client.GetStream())
txttempmsg.Text = (txtSend.Text)
writer.Write(txtUsername.Text + " # " + txtSend.Text)
AddMessage(txtUsername.Text, txttempmsg.Text + vbCrLf)
'txtmsg.Text="You:" + txtmessage.Text)
writer.Flush()
txtSend.Text = ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
When you have a problem trying to get something to work in your program. It is easier to create a test example that you can then use to figure out what is happening without dealing with a lot of other variables in your larger program. In your case I created a VB Winforms app, added a RichTextBox, two TextBox's and a Button. By doing so I am able to show that the function is working.
Public Class Form1
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & " :") 'Note added colon
box.SelectionColor = Color.Black
box.AppendText(txtSend) 'Note changed variable name to parameter name
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddMessage(txtUsername.Text, txttempmsg.Text)
End Sub
End Class
Example:

How to jump to a row of a DataView based on partial match search criteria?

Currently, my application uses the RowFilter property on an expression to search for a user-defined string within a DataView. Currently my code looks something like this:
Public Class MyClass
Private custView As DataView
Private Sub form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dsDataSet = <"DataAccessLayer call to SQL Stored Procedure">
custView = New DataView(dsDataSet.Tables(0))
custView.Sort = "Column Name"
Me.C1FlexGrid1.DataSource = custView
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Dim searchText As String = txtSearch.Text
Dim expression As String = "Column Name LIKE '" + searchText + "%'"
custView.RowFilter = expression
Me.C1FlexGrid1.DataSource = custView
End Sub
End Class
My goal is to modify the behavior of this such that instead of filtering out rows that do not meet the search results, it will keep all rows present but jump to the first instance of a partial match as the user types in the search box. If DataView.Find() supported wildcards I would be set, but unfortunately it doesn't.
The solution I've come up with is to use some iteration logic. However this is done on the object the DataView has been bound to and not the DataView itself. Although this code can be modified to do exactly that.
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
'Unselect all
Me.C1FlexGrid1.Select(-1, -1, True)
If txtSearch.Text <> "" And [column index] <> -1 Then
'Typed text
Dim s As String = txtSearch.Text.Trim.ToLower
Dim column As Int32 = [column index] + 1
'Recurse until match in first column is found
For i As Integer = 0 To Me.C1FlexGrid1.Rows.Count - 1
If C1FlexGrid1.GetData(i, column) <> Nothing Then
If C1FlexGrid1.GetData(i, column).ToString.ToLower.StartsWith(s) Then
Me.C1FlexGrid1.Select(i, column, True)
Exit Sub
End If
Else
MsgBox("Error message", vbOKOnly, "NO MATCHES")
'Reset search criteria
Call ResetSearch()
End If
Next
MsgBox("Error message", vbOKOnly, "NO MATCHES")
End If
End Sub

Calculating Profit in Visual Basic

This program is supposed to read in values from a text file and get a sum of all these values. It is then to use information gathered from a series of check boxes and text boxes to calculate the final profit.
As the code is written now, the profit is only correct if all check boxes are selected, but I need it to be correct if one, two, or all three are checked. Here is the current code
Option Strict On
Imports System.IO
Public Class Form1
Dim sum As Double
Dim fileRead As Boolean
Dim profit As Double
Private Sub menOpen_Click(sender As Object, e As EventArgs) Handles menOpen.Click
Dim ofd As New OpenFileDialog
ofd.Filter = "text files |*.txt|All Files|*.*"
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim selectedFileName As String = System.IO.Path.GetFileName(ofd.FileName)
If selectedFileName.ToLower = "profit.txt" Then
Dim line As String
Using reader As New StreamReader(ofd.OpenFile)
While Not reader.EndOfStream
line = reader.ReadLine
Dim value As Integer
If Integer.TryParse(line, value) Then
sum = sum + value
fileRead = True
End If
Console.WriteLine(line)
End While
End Using
Else
MessageBox.Show("You cannot use that file!")
End If
End If
End Sub
Private Sub menExit_Click(sender As Object, e As EventArgs) Handles menExit.Click
Me.Close()
End Sub
Private Sub radSales_CheckedChanged(sender As Object, e As EventArgs) Handles radSales.CheckedChanged
If radSales.Checked Then
profit = sum
End If
End Sub
Private Sub radSandO_CheckedChanged(sender As Object, e As EventArgs) Handles radSandO.CheckedChanged
If radSandO.Checked Then
If Trim(txtWages.Text) = "" Then
txtWages.Text = CStr(0)
End If
profit = (sum - CDbl(txtWages.Text) - CDbl(txtRent.Text) - CDbl(txtUtilities.Text))
End If
End Sub
Private Sub menComputeProfit_Click(sender As Object, e As EventArgs) Handles menComputeProfit.Click
If fileRead = False Then
MessageBox.Show("The file profit.txt has not been read in yet, the profit will be set to zero.")
sum = 0
End If
If chkWages.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtWages.Text) + Val(txtRent.Text) + Val(txtUtilities.Text))))
End If
If chkRent.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtRent.Text) + Val(txtWages.Text) + Val(txtUtilities.Text))))
End If
If chkUtilities.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtUtilities.Text) + Val(txtWages.Text) + Val(txtRent.Text))))
End If
txtAnswer.Text = profit.ToString
End Sub
End Class
Any help would be greatly appreciated.
One of those text inputs is most likely empty (as the error states). Even if it wasn't empty, it could still be an invalid Double value.
In order to safely check if the string can be converted to a double, you can use Double.TryParse, like this:
If Double.TryParse(value, number) Then
Console.WriteLine("'{0}' --> {1}", value, number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
Before you convert a string to double, check that the string is not empty. This is what error says. Afterwards you should check that the string in the box is actually numeric.
You are using TextChanged Event for txtAnswer
Private Sub txtAnswer_TextChanged(sender As Object, e As EventArgs) Handles txtAnswer.TextChanged
txtAnswer.Text = CStr(profit)
End Sub
So the above code is going to fire itself each time it changes! Just pop profit into txt Answer each time it is calculated
If chkWages.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtWages.Text)))
txtAnswer.text = profit
End If
If chkRent.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtRent.Text)))
txtAnswer.text = profit
End If
If chkUtilities.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtUtilities.Text)))
txtAnswer.text = profit
End If
A bit untidy but that should do it... you will need to do this whenever profit changed. And get rid of the TextChanged event.
UPDATED ANSWER FOR CLARITY
Ok I never add currency symbols so I'm not sure what CDbl(("$" & Val(Sum) - Val(txtWages.Text))) will do as it may treat it as a string character "$" rather than a currency.
Get rid of the "$" and just add the values... if you want to then stick the $ in front once calculation is complete say txtAnswer = $ & profit.toString

.NET fulltext autocomplete in a combobox. Any performance-positive way of overriding listitems?

I'm struggling to meet a demand from my supervisors. I really hope that someone could give some advice.
Basically there are places in our project where there is a big selection of options. The most concrete example is choosing a city in the world. The items are hundreds of thousands.
Using standard winforms controls and properties, one can search through a list fast.
The problem is that we're using a concatenation of city&district name for all the items. Essentially PREFIX autotomplete works but does not work as needed. The task is to filter and show items by any given string in any part of the item. Essentially a FULL TEXT search in the combobox.
Does anyone have an idea about switching autocomplete sources in runtime relatively qiuckly and handling the suggest/suggestappend event?
Also the project is in VB.NET, though any form of .NET advice will be extremely helpful.
Thanks!
UPDATE: The latest attempt using competent_tech's suggestion with some minor modifications.
Imports System.Data
Public Class Form1
Private _ErrorText As String
Private _CommandExecuted As Boolean
Private m_fOkToUpdateAutoComplete As Boolean
Private m_sLastSearchedFor As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Me.SetStatusText("Loading...")
Me._ErrorText = ""
Me.Cities.Clear()
Me.BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
Me._CommandExecuted = True
Me.Ara_airportsTableAdapter.Fill(Me.Cities.ara_airports)
Catch ex As Exception
_ErrorText = ex.Message
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If Me._ErrorText = "" Then
Me.SetStatusText(Me.Cities.ara_airports.Count & " Records loaded")
Else
Me.SetStatusText(Me._ErrorText)
End If
Me.BindingSource.ResetBindings(False)
End Sub
Private Sub SetStatusText(ByVal sText As String)
Me.Text = sText
End Sub
Private Sub cboPort_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboPort.KeyDown
Try
If e.KeyCode = Keys.Up OrElse e.KeyCode = Keys.Down Then
m_fOkToUpdateAutoComplete = False
Else
m_fOkToUpdateAutoComplete = True
End If
Catch theException As Exception
' ...
End Try
End Sub
Private Sub cboPort_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboPort.KeyUp
Try
If m_fOkToUpdateAutoComplete Then
With cboPort
If .Text.Length >= 2 Then
Dim cSuggestions As IList
Dim sError As String = ""
m_sLastSearchedFor = .Text
cSuggestions = GetSuggestions(m_sLastSearchedFor)
.DataSource = Nothing
If cSuggestions IsNot Nothing Then
.BindingContext = New BindingContext
.DisplayMember = "CName"
.ValueMember = "id"
.DataSource = New BindingSource(cSuggestions, Nothing)
System.Threading.Thread.Sleep(10)
System.Windows.Forms.Application.DoEvents()
.DroppedDown = True
.Text = m_sLastSearchedFor
If .Text.Length > 0 Then .SelectionStart = .Text.Length
End If
End If
End With
End If
Catch theException As Exception
' ...
End Try
End Sub
Private Function GetSuggestions(ByVal searchFor As String) As IList
BindingSource.Filter = "CName LIKE '%" & searchFor & "%'"
Return BindingSource.List
End Function
End Class
The way we address this with very large sets of data (full set of drug information) is:
1) Handle the combo's TextChanged event
2) Within this event, get the list of suggestions that match the user's current input from the database. We leverage the power of database searching to find matches anywhere within the string.
3) When the suggestions are retrieved, bind them to the combobox
4) Wait for a little bit (500ms) to let the UI catch up (we use a combination of System.Threading.Thread.Sleep and System.Windows.Format.Application.DoEvents()).
A couple of notes on this approach:
1) Nothing is bound to the list when the form is first opened
2) We wait until the user has entered at least 4 characters before we start searching to reduce the hit on the DB and improve the user experience (you don't want to show all of the matches for A, for example).
Update with code to show full solution:
Here are some additional notes and code to show the actual process.
The ComboBox should be configured with all of the properties set to their default values with the exception of:
AutoCompleteMode = SuggestAppend
PreferredDropDownSize = 0, 0
Here is the code that we use for our specific situation (searching first four chars) with a placeholder for retrieving and assigning the data:
Private m_fOkToUpdateAutoComplete As Boolean
Private m_sLastSearchedFor As String = ""
Private Sub cboName_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboName.KeyDown
Try
' Catch up and down arrows, and don't change text box if these keys are pressed.
If e.KeyCode = Keys.Up OrElse e.KeyCode = Keys.Down Then
m_fOkToUpdateAutoComplete = False
Else
m_fOkToUpdateAutoComplete = True
End If
Catch theException As Exception
' Do something with the error
End Try
End Sub
Private Sub cboName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboName.TextChanged
Try
If m_fOkToUpdateAutoComplete Then
With cboName
If .Text.Length >= 4 Then
' Only do a search when the first 4 characters have changed
If Not .Text.Substring(0, 4).Equals(m_sLastSearchedFor, StringComparison.InvariantCultureIgnoreCase) Then
Dim cSuggestions As IEnumerable
Dim sError As String = ""
' Record the last 4 characters we searched for
m_sLastSearchedFor = .Text.Substring(0, 4)
' And search for those
cSuggestions = GetSomeSuggestions(m_sLastSearchedFor) ' Your code here
.DataSource = Nothing
If cSuggestions IsNot Nothing Then
' Because this can use the same data source as the list, ensure that
' the bindingcontexts are different so that the lists are not tied to each other
.BindingContext = New BindingContext
.DataSource = cSuggestions
' Let the UI process the results
System.Threading.Thread.Sleep(10)
System.Windows.Forms.Application.DoEvents()
End If
End If
Else
If Not String.IsNullOrEmpty(m_sLastSearchedFor) Then
' Clear the last searched for text
m_sLastSearchedFor = ""
cboName.DataSource = Nothing
End If
End If
End With
End If
Catch theException As Exception
' Do something with the error
End Try
End Sub