I want to replace some characters from a string. I used the Replace command. But this is not working - vb.net

I am writing some code in VB.Net to subtract one string from another string, but this is not working. in output nothing is changed in the target string. But there is no error message. Please help. Thanks.
If RadioButton1.Checked Then
TextBox1.Text = ""
positive = (TextBoxp1.Text + TextBoxp2.Text + TextBoxp3.Text)
negative = (TextBoxn1.Text + TextBoxn2.Text + TextBoxn3.Text)
findstring = Replace(positive, negative, "")
TextBox1.Text = findstring
End If

The concatenation symbol in vb.net is the ampersand (&). You may get unexpected results it you use the plus sign and the strings contain numbers. Parenthesis are not necessary to evaluate an expression except to establish order of calculation when it conflicts with order of precedence.
You are using the vb.net Strings.Replace method. I would use the .net String.Replace method because it is easier to move between .net languages when you get used to using .net methods instead of vb specific methods.
This method takes the original string in this case negative and looks for the entire positive string. If it finds the entire string it replaces it with the empty string.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim positive = "b" & "cd" & "ef"
Dim negative = "abc" & "def" & "ghi"
TextBox1.Text = negative.Replace(positive, "")
'Result is aghi
End Sub
If you are trying to remove individual letters from a string then you will have to use a loop. Luckily for us a String is an array of Char.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim positive = "ceg"
Dim negative = "abcdefg"
For Each ch As Char In positive
negative = negative.Replace(ch, "")
Next
TextBox1.Text = negative
'Result abdf
End Sub

You are making this way too complicated. If what you want is to remove a substring from within a string use replace like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
If rdbtnRemove.Checked Then
txtResultString.Text = Replace(txtLargeString.Text, txtSearchString.Text, "")
End If
End Sub
All you need is two radio buttons, three text boxes and a button. If you enter 1121221114141 in the txtLargeString text box, 2122 in the txtSearchString text box and execute the code, the result is 111114141 which is the result of removing the txtSearchString input from the txtLargeString input.
Or if as #Mary suggested you want to use the more modern version of replace use this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
If rdbtnRemove.Checked Then
txtResultString.Text = txtLargeString.Text.Replace(txtSearchString.Text, "")
End If
End Sub

Related

User enters letter then button computes position from a string using VB

I am using indexOf but I cannot figure out where I made a mistake as the output gives a -1.
I realise I can copy the whole statement paragraph into the last line of the output but I was hoping it could pull it straight from the label.
Public Class Form1
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
Dim statement As String
Dim letter As String
statement = CStr(lblStatement.Text)
letter = CStr(txtLetter.Text)
txtOutput.Text = CStr(lblStatement.Text).IndexOf("letter")
'txtOutput.Text = letter.ToUpper & " first occurs in position " & statement.IndexOf(statement) & "."
End Sub
End Class
Here is a picture of the form:
Update: Thanks to #ADyson and #Slugsie for taking the time to respond to my call for help. As #Slugsie noted it was indeed down to the lower case in my screenshot. I am now researching how to make it work without being case-sensitive.
Final code
Public Class Form1
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
txtOutput.Text = lblStatement.Text.IndexOf((txtLetter.Text).ToUpper)
End Sub
End Class
.IndexOf("letter")
is looking for the literal text letter within the data the user enters in the text. in VB.NET (and most other programming languages), anything enclosed within quote marks is treated as a fixed string of text, to be interpreted as-is rather than processed or treated as program code.
To make it look for the contents of the letter variable instead (which looks like what you were intending) simply remove the quote marks:
.IndexOf(letter)
As an aside, your whole code could be much reduced - primarily the use of CStr is unnecessary, because the Text properties of the textbox and label already return a string - meaning you don't need to use CStr convert it - and also because you're not making use of all the variables you declared either.
You could re-write your whole sample much more succinctly as:
Public Class Form1
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
txtOutput.Text = lblStatement.Text.IndexOf(txtLetter.Text)
End Sub
End Class

How to check a text box for a certain character and replace with a different string in the same spot

I am working on a little morse code translation project and I cannot figure out how to detect when a certain key is in a textbox and replace it with the corresponding morse code dots and dashes in the correct spot.
For example if you type in "a b c" then i would like the program to check and put
".- -... -.-."
but it also needs to be dynamic so if you change up the order of your letters it can update the translation.
as of right now i have a key checking system where you can only type in one forward line and if you mess up you have to clear the whole box. thank you!
Here is a basic example of what I was suggesting in my comments above, i.e. using two separate TextBoxes and translating the whole text every time:
Private morseCodeDictionary As New Dictionary(Of Char, String) From {{"a"c, ".-"},
{"b"c, "-..."},
{"c"c, "-.-."}}
Private Sub inputTextBox_TextChanged(sender As Object, e As EventArgs) Handles inputTextBox.TextChanged
outputTextBox.Text = String.Join(" ",
inputTextBox.Text.
ToLower().
Select(Function(ch) morseCodeDictionary(ch)))
End Sub
Here's an implementation that doesn't use LINQ, so may be more understandable:
Private Sub inputTextBox_TextChanged(sender As Object, e As EventArgs) Handles inputTextBox.TextChanged
Dim characterStrings As New List(Of String)
For Each ch As Char In inputTextBox.Text
characterStrings.Add(morseCodeDictionary(ch))
Next
outputTextBox.Text = String.Join(" ", characterStrings)
End Sub

Alternative Process

I have 2 buttons and a DataGridView with 2 Columns (0 & 1).
The 1st button transfers a randomized cell from the Column(1) to a TextBox. Then, it stores that Cell in variable (a), plus the cell that opposites it in variable (b).
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rnd As New Random
Dim x As Integer = rnd.Next(0, Form1.DataGridView1.Rows.Count)
Dim y As Integer = 1
Dim a As String = Form1.DataGridView1.Rows(x).Cells(y).Value
Dim b As String = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
The 2nd button, however, is supposed to compare if another TextBox's text has the same string variable (b) has as Strings. Now, if so, then it has to display a certain message and so on...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox4.Text = b Then '<<< ISSUE HERE!
MsgBox("Correct! ^_^")
ElseIf TextBox4.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub
The problem is that the variable (b) is surely not shared across the two "private" subs. And so, there is NOTHING to compare to in the 2nd button's sub! I presume that the solution here is to split the "randomization process" into a separate function, then execute it directly when the 1st button gets activated. Furthermore, that function's variables have to be SHARED somehow, and I certainly don't know how!
Thanks for Mr. Olivier, the code has been improved significantly! Yet, I still encounter a "wrong" comparison issue, somehow!
Dim RND As New Random
Dim x As Integer
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
x = RND.Next(0, Form1.DataGridView1.Rows.Count)
tbxRoll.Text = GetCell(x, 1)
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If tbxSubmit.Text = GetCell(x, 0) Then
MsgBox("Correct! ^_^")
ElseIf tbxSubmit.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub</code>
Well, unbelievably, I read a guide about "comparison operations" in VB.net and tried out the first yet the most primal method to compare equality - which was to use .Equals() command - and worked like a charm! Thank God, everything works just fine now. ^_^
If tbxSubmit.Text.Equals(GetCell(x, 0)) Then
Alright now... This is going to sound weird! But, following Mr. Olivier's advise to investigate "debug" the code, I rapped the string I'm trying to compare with brackets and realized that it's been outputted after a break-line space! So, I used the following function to remove the "white-space" from both of the comparison strings! And it bloody worked! This time for sure, though. ^_^
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
If RemoveWhitespace(tbxSubmit.Text) = RemoveWhitespace(GetCell(x, 0)) Then
Turn the local variables into class fields.
Dim rnd As New Random
Dim x As Integer
Dim y As Integer
Dim a As String
Dim b As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
x = rnd.Next(0, Form1.DataGridView1.Rows.Count)
y = 1
a = Form1.DataGridView1.Rows(x).Cells(y).Value
b = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
These fields can now be accessed from every Sub, Function and Property.
Of course Button3_Click must be called before Button2_Click because the fields are initialized in the first method. If this is not the case then you should consider another approach.
Create a function for the Cell access
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) _
As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
And then compare
If TextBox4.Text = GetCell(x, y - 1) Then
...
And don't store the values in a and b anymore. If y is always 1 then use the numbers directly.
If TextBox4.Text = GetCell(x, 0) Then
...
One more thing: give speaking names to your buttons in the properties grid before creating the Click event handlers (like e.g. btnRandomize). Then you will get speaking names for those routines as well (e.g. btnRandomize_Click).
See:
- VB.NET Class Examples
- Visual Basic .NET/Classes: Fields

Case Statement not working with String Literals

Hi all I am trying to learn VB and am having trouble with some code I am using. I would like my program to output a specific number based on if a check box is checked using case statements but my code is not working.
Public Class frmBTPW
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
Dim dblhdr As Double
Dim dblfdr As Double
Dim dbltdr As Double
dblhdr = 24
dblfdr = 35
dbltdr = 50
Select Case "Power Wash Rental"
Case "Half Day Rental"
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
Case "Full Day Rental"
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
End Select
End Sub
Private Function Button1_Click() As CheckBox
Throw New NotImplementedException
End Function
End Class
Help would be greatly appreciated.My code isn't outputting anything in the text-box.
Beyond case statements, respectfully I think you should read up on the distinction between a literal value and a variable. "Power Wash Rental" is nothing more than a series of characters, AKA a string: (In this case "P" followed by "o" etc.) Likewise, "Half Day Rental" is a series of characters, "H" followed by "a" etc.)
"Power Wash Rental" is a literal string. So is ""Half Day Rental" and of course they will never match.
Whereas:
Dim A as string
A = TextBox1.text
Now, A is a variable. It is a string which contains whatever series of characters (text) is typed into the textbox.
This is a simple way to do it.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chkhd.tag = 24 ' store values in the check boxes
chkfd.tag = 35 ' using the tag property
chktd.tag = 50 ' and later add up the values
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
dim total as double = 0
total += IF(chkhd.checked, cdbl(chkhd.tag), 0)
total += IF(chkfd.checked, cdbl(chkfd.tag), 0)
total += IF(chktd.checked, cdbl(chktd.tag), 0)
msgbox(total)
End Sub
However, I think you might want radio buttons instead of checkboxes.
Checkboxes can all be checked. Radio buttons can only have one at a time.
This solution allows you to keep your price with the checkbox -- you could do this in the form designer instead of form load.
I would recommend reading up on Case Statements. Currently you will never get anywhere as your using a string to what, nothing. You also do not need a case for this... Also if the first condition is true and the last one is as well, the last one win's for setting the text, didn't know if you had this there for a reason or not?
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
As others have stated your Case statement isn't working because you are using string literals to compare "Power Wash Rental" to "Half Day Rental" which will always be false. Plutonix was also correct in saying that a ComboBox for the rental duration should be used. The only reason not to be is if you were calculating cumulative rental days/amounts; however in that situation you should be using some sort of NumericUpDown for your multiplier against a time duration.
Here is an example that should help you get started. You could make the structure into a type of keyed collection or make it a wrapper class for a dictionary object which would make be easier to use in code. The following may not be exactly plug-and-play with your project, however it should help give you some ideas on how to handle the situation.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.ComboBox1.Items.AddRange({PowerWashRentals.halfDayText, PowerWashRentals.FullDayText, PowerWashRentals.TwoDayText})
AddHandler ComboBox1.SelectedValueChanged, AddressOf Me.ComboBox1_SelectedChanged
End Sub
Private Sub ComboBox1_SelectedChanged(sender As Object, e As EventArgs)
Dim cBox As ComboBox = DirectCast(sender, ComboBox)
Select Case cBox.SelectedItem.ToString
Case PowerWashRentals.halfDayText
Label1.Text = PowerWashRentals.HalfDayPrice.ToString
Case PowerWashRentals.FullDayText
Label1.Text = PowerWashRentals.FullDayPrice.ToString
Case PowerWashRentals.TwoDayText
Label1.Text = PowerWashRentals.TwoDayPrice.ToString
End Select
End Sub
End Class
Public Structure PowerWashRentals
Public Const HalfDayPrice As Double = 24
Public Const FullDayPrice As Double = 35
Public Const TwoDayPrice As Double = 50
Public Const halfDayText As String = "Half Day Rental"
Public Const FullDayText As String = "Full Day Rental"
Public Const TwoDayText As String = "Two Day Rental"
End Structure

Only get characters surrounded by " "

I'm Currently writing a program that will convert my code into Pseudo Code but I'm having the problem that I cannot figure out how to get Only text that is surrounded by " " and comes after the word print.
Currently have
Dim str() As String = TextBox1.Text.Split()
If str.Contains("Print") Then
End If
Nothing
Here is one way. Instead of splitting and then checking for Print, Check for Print first and then split it.
Tried and Tested
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Contains("Print") Then
Dim ar As String = TextBox1.Text.Substring(TextBox1.Text.IndexOf("Print"))
Dim splitted() As String = Split(ar, """")
If splitted.Length > 1 Then MessageBox.Show(splitted(1))
End If
End Sub
If the string is say This "is" a great Print Job! "Nice Work" then the above code should give you Nice Work