How can I display a name in a different sequence using strings? - vb.net

I'm having trouble with a problem that I was assigned for my Visual Basic 2012 class. The instructions are below. So far, I have it displaying only the first name entered, and nothing else. How can I make it to display both the first name and the last name in the sequence requested?
String Problem: Enter your first and last name in a text box. Take the name and display it in a label box showing the last name, first name.
Text Box Entry: Jane Doe
Label Box: Doe, Jane
The code I have so far is below. Thanks for any help!
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
firstlabel.Text = firstname
fulltextbox.Focus()
End Sub
Private Sub fulltextbox_TextChanged(sender As Object, e As EventArgs)
firstlabel.Text = String.Empty
fulltextbox.SelectAll()
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub

You are on the right track by first determining where the space is located:
indexnum = fullname.IndexOf(" ")
Now based on this index, you can split the string into two strings, firstname and lastname:
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
You need to use indexnum+1, instead of indexnum, otherwise you will include the spacing character.
Finally you group them together again by using the string concatenation operator (&):
firstlabel.Text = lastname & ", " & firstname
The final method thus looks like:
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
firstlabel.Text = lastname & ", " & firstname
fulltextbox.Focus()
End Sub

Note, this won't work if your using middle initials. Also, I would remove fulltextbox.SelectAll() from fulltextbox_TextChanged
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim Names() As String = fulltextbox.Text.Split(" "c)
If Names.Count = 2 Then
firstlabel.Text = Names(1) + ", " + Names(0)
ElseIf Names.Count = 0 Then
MessageBox.Show("Please enter name.")
Else
MessageBox.Show("Invalid Nmae entered.")
End If
fulltextbox.Text = ""
End Sub

Related

LINQ Query Null Error

I have am making an email contact search, where I am supposed to open a text file using the OpenFileDialog, and then split it to an array and search using LINQ. I have the openFileDialog working, but when I run my LINQ query, I get the object reference not set to an instance of an object error. Option Infer is on, and as far as I can tell this is set up exactly like some of the examples in my textbook. Can anyone point me in the right direction??? (textFile is defined as a class variable above the first button code: "Dim textFile(2) As String".
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnOpen.Click
OpenFileDialog1.ShowDialog()
textFile(2) = OpenFileDialog1.FileName
lstOutput.DataSource = IO.File.ReadAllLines(textFile(2))
lstOutput.SelectedItem = Nothing
End Sub
Private Sub btnNameSearch_Click(sender As Object, e As EventArgs) Handles btnNameSearch.Click
Dim queryName = From line In textFile
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let email = data(2)
Where firstName = txtName.Text
Select firstName, lastName, email
lstName.DataSource = queryName.ToList
End Sub
Edit: Code breaks on line 21 "Let data=line.Split(","c)
You're using the filename as the string that LINQ is querying against. You need to use the file contents itself.
Change your code to something like this:
Private lines() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnOpen.Click
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
textFile(2) = OpenFileDialog1.FileName
lines = IO.File.ReadAllLines(textFile(2))
lstOutput.DataSource = lines
lstOutput.SelectedItem = Nothing
End If
End Sub
Private Sub btnNameSearch_Click(sender As Object, e As EventArgs) Handles btnNameSearch.Click
Dim queryName = From line In lines
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let email = data(2)
Where firstName = txtName.Text
Select firstName, lastName, email
lstName.DataSource = queryName.ToList
End Sub

Paste Intercept event failure

I want to intercept a paste event for a FIRST NAME textbox so that if the user pastes "Joe Smith, PhD", they will get "Joe" in the FIRST NAME textbox, and they will see "Smith, PhD" in the LAST NAME textbox. Instead, what I get is "Joe Smith,PhDJoe" in FIRST NAME textbox, and "Smith, PhD" in LAST NAME textbox. I added a messagebox as a breakpoint for me and if I uncomment that line, the msgbox displays and then the sub works perfectly. So, is this a timing issue (Windows 10/VS2015 if that matters)?
There are many posts on how to intercept paste events, and my code below is based on that. What am I doing wrong?
Public Class test
Private Sub TBfname_PASTE(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TBFname.KeyDown
Dim Pasting As String = Clipboard.GetText()
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
Dim SplitWhere As Int64 = 0
Dim words = Pasting.Split(" "c)
Dim firstWord = words(0)
If Pasting.Contains(" ") Then
SplitWhere = Pasting.IndexOf(" ")
Dim LN As String = ""
Dim long2 As Int64 = Pasting.Length - SplitWhere - 1
If long2 > 0 Then
LN = Pasting.Substring(SplitWhere + 1, long2)
TBLname.Text = LN
End If
' MsgBox(Pasting & " vs " & TBFname.Text)
TBFname.Text = firstWord
End If
e.Handled = True
End If
End Sub
End Class
One thing you could to is declare firstword as a Form level variable
Private firstWord As String
and then assign it in TBfname_KeyDown
firstWord = words(0)
Then in the KeyUp event re-assign TBfname.Text
Private Sub TBfname_KeyUp(sender As Object, e As KeyEventArgs) Handles TBfname.KeyUp
TBfname.Text = firstWord
End Sub

Windows Form doesn't disable on Enabled = False

I have these two subroutines which handle a button click event for two buttons on a form. Each one causes another smaller form to be displayed over the window which requires user input before the user may continue.
In both cases I have used Enabled = False to disable to main form while the smaller form is active. In the first Sub, AddNewPatientButton_Click, this has the desired effect of disabling the main form. However, for DeletePatientButton_Click, this has no effect.
Below is the code for the event handlers:
Private Sub AddNewPatientButton_Click(sender As Object, e As EventArgs) Handles AddNewPatientButton.Click
NewPatientForm.Show()
Enabled = False
End Sub
Private Sub DeletePatientButton_Click(sender As Object, e As EventArgs) Handles DeletePatientButton.Click
AreYouSureForm.Show()
Enabled = False
If AreYouSureForm.yesSelected Then
Dim sqlQuery As String = "DELETE FROM Patients WHERE "
Dim firstName As String = PatientDataGridView.CurrentRow.Cells.Item(0).Value.ToString()
Dim lastName As String = PatientDataGridView.CurrentRow.Cells.Item(1).Value.ToString()
Dim dOB As String = PatientDataGridView.CurrentRow.Cells.Item(2).Value.ToString()
dOB = dOB.Substring(0, 2) & dOB.Substring(3, 2) & dOB.Substring(6, 4)
sqlQuery = sqlQuery & "Firstname = '" & firstName & "' AND Surname = '" & lastName & "' AND DateOfBirth = '" & dOB & "'"
DatabaseModule.AddOrDelete(sqlQuery, True, True)
End If
Enabled = True
End Sub
And here is the code for the NewPatientForm that the first event brings up:
Public Class NewPatientForm
Private Sub NewPatientForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Populate the year drop-down box with all of the years between now and 1900
Dim year As Integer = Date.Today.Year()
Do Until year = 1899
YearComboBox.Items.Add(year)
year -= 1
Loop
End Sub
Private Sub CancelAddButton_Click(sender As Object, e As EventArgs) Handles CancelAddButton.Click
PatientDatabaseForm.Enabled = True
Me.Close()
End Sub
Private Sub OkayButton_Click(sender As Object, e As EventArgs) Handles OkayButton.Click
Dim sqlQuery As String = "INSERT INTO Patients (Firstname, Surname, DateOfBirth) VALUES ("
'Get inputs
Dim firstName As String = FirstNameTextBox.Text
Dim surname As String = LastNameTextBox.Text
Dim dOB As String = DayComboBox.Text & "-" & MonthComboBox.Text & "-" & YearComboBox.Text
'Build sql insert string from inputted values
If (firstName <> "") And (surname <> "") And (dOB <> "--") Then 'If no input, then display message
sqlQuery = sqlQuery & "'" & firstName & "', "
sqlQuery = sqlQuery & "'" & surname & "', "
sqlQuery = sqlQuery & "'" & dOB & "')"
DatabaseModule.AddOrDelete(sqlQuery, True, False)
Else
MessageBox.Show("Invalid input")
End If
End Sub
End Class
And the code for the AreYouSureForm that the second event brings up:
Public Class AreYouSureForm
Public yesSelected As Boolean
Public Sub YesButton_Click(sender As Object, e As EventArgs) Handles YesButton.Click
yesSelected = True
Close()
End Sub
Private Sub NoButton_Click(sender As Object, e As EventArgs) Handles NoButton.Click
yesSelected = False
Close()
End Sub
End Class
I'm probably just missing something really stupid, but I can't see it :(
Any help would be appreciated, thanks

transfering fixed words in multiline textbox in visual basic to seperate single line textboxes

I am having problem in visual basic textbox so my actual problem is i have a Multiline textbox1 containing FirstName="JOHN" in one line and LastName="SMITH" in the newline and i want to transfer only JOHN in separate singleline textbox2 and SMITH in other singleline textbox3.
i want this to happen on click of copy button.
The lefthanside of the textbox1 like FirstName,LastName remains constant whereas the rightside like JOHN,SMITH are changing in nature.
I have created a separate function and i have tried so far as
Public Class Form1
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
End Class
here's the link to screenshot of what i want to accomplish.
http://tinypic.com/r/2mcev5w/8
Thanks in advance
I think you could separate the text from the textbox by new lines. Something like:
Dim itemsInTextBox as String() = TextBox1.Text.Split(vbCrLf.toCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName as String = itemsInTextBox(0).Split("=".toCharArray)(1)
Dim secondName as String = itemsInTextBox(1).Split("=".toCharArray)(1)
This is assuming your lines in the textbox are separated by new lines. If it is separated by something else, just put that in the split method. This also keeps the quotation marks (do you want this?)
EDIT: for setting other textboxes
TextBox2.Text = firstName
TextBox3.Text = secondName
EDIT2: You have to create those variables on button click. If you do it globally, it will be run before your TextBox1 exists.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
Your sample and your description are different. In your sample you use FIRSTNAME=JOHN and in your description you use first-name="john" which are very different.
Lets use your sample. Your test should look like this.
TextBox2.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
TextBox3.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
Of you try it like this, you will see it's not returning the right information.
You'll have to split each line and then split these line again with the = sign like you did.
Function GetValue(ByVal data As String, ByVal key As String) As String
Dim lines() As String = data.Split(Chr(10))
For Each line As String In lines
line = line.Trim()
Dim subData() As String = line.Split("="c)
If subData(0) = key Then
Return subData(1)
End If
Next
Return ""
End Function
Sub Main()
Dim data As String
data = "FIRSTNAME=JOHN" & Environment.NewLine & "LASTNAME=SMITH"
Console.WriteLine(GetValue(data, "FIRSTNAME"))
Console.WriteLine(GetValue(data, "LASTNAME"))
Console.ReadLine()
End Sub
Just move the declaration of the itemsList into the sub for the copy.
EDIT: Also need to move the declaration of the strings
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub

How to get a information from a listbox to textboxes with radio buttons

I have been trying to figure out what I am doing wrong. I have two radio buttons one for a new user a the other for an existing user. The new user radio button takes the information input into the textboxes and adds to the list box. The existing user button is supposed to take the line selected in the listbox and break it up then put it back into my textboxes. I have written code for the radio buttons but they are not working properly. How can I get the information to process correctly and show in the textboxes? I have tried a split and a function but this was unsuccessful. Can anyone help? This is what I have for the radio buttons so far I can post the rest of the code if you need me to.
Private Sub rbtnNew_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnNew.CheckedChanged
lstCustomer.Items.Add(RevName(txtName.Text.ToUpper) & " , " & (txtAddress.Text.ToUpper) & " , " & (txtCity.Text.ToUpper))
End Sub
Private Sub rbtnExisting_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnExisting.CheckedChanged
Dim name1 As String
Dim address2 As String
Dim city2 As String
Dim output() As String
name1 = txtName.Text
address2 = txtAddress.Text
city2 = txtCity.Text
output = Split(lstCustomer.SelectedItem.ToString(), ",")
txtName.Text = output(0)
txtAddress.Text = output(1)
txtCity.Text = output(2)
lstResults.Items.Clear()
txtChairs.Clear()
txtSofas.Clear()
End Sub
End Class
In this case, the radiobuttons are very difficult to manage when they have the AutoCheck property set to True. Anyway I give you a couple of possible solutions:
Solution #1 (AutoCheck property set to True):
Private Sub rbtnNew_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbtnNew.CheckedChanged
Static wasInvoked As Boolean
If Not wasInvoked Then
If rbtnNew.Checked Then
lstCustomer.Items.Add(RevName(txtName.Text.ToUpper) & " , " & (txtAddress.Text.ToUpper) & " , " & (txtCity.Text.ToUpper))
Else
If lstCustomer.SelectedItem Is Nothing Then
wasInvoked = True
rbtnNew.Checked = True
wasInvoked = False
MessageBox.Show("Please select a customer from the list.")
End If
End If
End If
End Sub
Private Sub rbtnExisting_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rbtnExisting.CheckedChanged
If rbtnExisting.Checked Then
Dim name1 As String
Dim address2 As String
Dim city2 As String
Dim output() As String
name1 = txtName.Text
address2 = txtAddress.Text
city2 = txtCity.Text
output = Split(lstCustomer.SelectedItem.ToString(), ",")
txtName.Text = output(0)
txtAddress.Text = output(1)
txtCity.Text = output(2)
lstResults.Items.Clear()
txtChairs.Clear()
txtSofas.Clear()
End If
End Sub
Solution #2 (RadioButtons's AutoCheck property set to False):
Private Sub rbtnNew_CheckedChanged(sender As Object, e As System.EventArgs) Handles rbtnNew.CheckedChanged
rbtnExisting.Checked = Not rbtnNew.Checked
End Sub
Private Sub rbtnExisting_CheckedChanged(sender As Object, e As System.EventArgs) Handles rbtnExisting.CheckedChanged
rbtnNew.Checked = Not rbtnExisting.Checked
End Sub
Private Sub rbtnNew_Click(sender As Object, e As System.EventArgs) Handles rbtnNew.Click
If Not rbtnNew.Checked Then
rbtnNew.Checked = True
lstCustomer.Items.Add(RevName(txtName.Text.ToUpper) & " , " & (txtAddress.Text.ToUpper) & " , " & (txtCity.Text.ToUpper))
End If
End Sub
Private Sub rbtnExisting_Click(sender As Object, e As System.EventArgs) Handles rbtnExisting.Click
If Not rbtnExisting.Checked Then
If lstCustomer.SelectedItem Is Nothing Then
MessageBox.Show("Please select a customer from the list.")
Else
rbtnExisting.Checked = True
Dim name1 As String
Dim address2 As String
Dim city2 As String
Dim output() As String
name1 = txtName.Text
address2 = txtAddress.Text
city2 = txtCity.Text
output = Split(lstCustomer.SelectedItem.ToString(), ",")
txtName.Text = output(0)
txtAddress.Text = output(1)
txtCity.Text = output(2)
lstResults.Items.Clear()
txtChairs.Clear()
txtSofas.Clear()
End If
End If
The radiobutton checkedchanged event may be trigger either it is checked or unchecked. Make sure check the value/attribution of the radiobutton in the event function.
Edit: Do you have the error-checking code for the case that listbox has no items at all? Since no item is seleced in listbox will cause ListBox.SelectedItem return null or something which the Split() function can not handle.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditem%28v=vs.110%29.aspx
In addition, using the string manipulation function provided by the system, such as join(), concat().
http://msdn.microsoft.com/en-us/library/aa903372%28v=vs.71%29.aspx
Check the size/length of the resulting string array from split().