How to use two forms to search in one and display the records to the other using Visual Basic 2010, SQL Server 2008 - sql

I have 2 forms in my visual basic 2010 project. Both are connected with an SQL 2008 Server where i keep a db with customers records(name,surname,address, etc).
What i want to do is to give certain criteria in the first form, lets say name,and hit a search button. The program should search the db if the specified name exists.If it exists i want to show the results in the second form. By results i mean the name , surname, address,etc. If it does not exist i want to prompt the user to insert data into the db.
The problem is that i know how to do this work in a single form but not how to make the two forms "communicate" with each other (meaning that one does the search and the other the projection-adding part).
Any help is appreciated
Edit
I am sorry guys but i cannot figured it out. I tried setting the filters but all i get is errors. I will post whatever i have written so far in case someone can help me out. So here it is.
As i stated earlier i know how to search for the data in a single form(lets call it DisplayForm). As Olivier mentioned i have textboxes for the records, a combo box with the search criteria(name , surname,id) and a Search button that perfoms the search and populates the text boxes. The code for the search button is this:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim intPosition As Integer
'Combo box code
Select Case cboField.SelectedIndex
Case 0
ObjDataView.Sort = "surname"
Case 1
ObjDataView.Sort = "id"
End Select
If cboField.SelectedIndex = 0 Then
intPosition = ObjDataView.Find(txtSearch.Text)
ElseIf cboField.SelectedIndex = 1 Then
intPosition = ObjDataView.Find(CType(txtSearch.Text, Integer))
End If
If intPosition = -1 Then
MessageBox.Show("No customer found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)
Else
objCurrencyManager.Position = intPosition
End If
End Sub
I want this procedure be done in a second form (lets call it FormSearch) and populate the textboxes in form DisplayForm. I know that it is easy enough for someone that knows VB but i am tottally a newbie and desperatly need help.
Thanks a lot for any advice

In your display form add this code
Public Sub SetFilter(name as String)
' Set the filter here
End Sub
In your filter form do this
DirectCast(Application.OpenForms(0), DisplayForm).SetFilter(NameTextBox.Text)
Here I assume that DisplayForm is your main form and that it's name is DisplayForm. You would call this in a button click event hanlder, for instance.
EDIT in response to comment:
You said that you know how to do it on a single form. I do not know how you do it, but probably you have textboxes for the name, the address, etc. that you are looking for. Then probably you press a button called btnSearch. By pressing this button you trigger
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch_Click.Click
' The search logic goes here
End Sub
What I am telling you is to replace btnSearch_Click by Public Sub SetFilter(name as String) that is public. You would move those search fields and the button to the second form and from there call SetFilter of the first form in order to communicate with it and tell it to search a customer. In my example, I pass only a name, but I left it up to you to pass more parameters as required.
Assuming that your customer form is called "DisplayForm", you could access it like this
Dim cust As DisplayForm
cust = DirectCast(Application.OpenForms("DisplayForm"), DisplayForm)
cust.SetFilter(NameTextBox.Text)
My answer was only about the communication between the two forms, assuming that you already managed the other part.
Searching for "VB.NET Tutorial: Working With Data" on YouTube results in six videos on this subject. Video #3 in particular shows how to use filters.
EDIT #2. Here is a little more help:
I do not know how you are opening the two forms. Since you need a reference to the display form in the search form, it is easier to open the search form as the main form at application startup. At Form_Load in the search form, you then open the display form by code
Code in the search form:
' Reference to the display form
Private _displayForm As DisplayForm
' Create the display form and open it
Private Sub SearchForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
_displayForm = New DisplayForm()
_displayForm.Show()
End Sub
' Get the search parameters and tell the display form to set the filter
Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
Dim field As String, search As Object
Select Case cboField.SelectedIndex
Case 0
field = "surname"
search = txtSearch.Text
Case 1
Dim n As Integer
field = "id"
If Integer.TryParse(txtSearch.Text, n) Then
search = n
Else
MessageBox.Show("Please enter a number for id search", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)
Return
End IF
End Select
_displayForm.SetFilter(field, search)
End Sub
Code in the display form that actually performs sorting and searching:
Public Sub SetFilter(ByVal field As String, ByVal search As Object)
Dim intPosition As Integer
ObjDataView.Sort = field
intPosition = ObjDataView.Find(search)
If intPosition = -1 Then
MessageBox.Show("No customer found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)
Else
objCurrencyManager.Position = intPosition
End If
End Sub

Related

Visual Basic find and display

I have made a program in Visual Basic. It's a contact book where the user can enter a friend's name as the key and contact which is stored as a value. Both are entered via TextBoxes and the information is then displayed in a ListBox.
The following code is for my search address button where I enter the contact name in TextBox4 and it displays the address in TextBox3. The problem I'm having with my code is that after I enter more contacts into my ListBox and I click the find button it does display the address, but also the error message which is intended to be used if the contact does not exist.
I'm a beginner to programming and looking to see what is wrong with my code.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
TextBox3.Clear()
For Each x In MyAddressBook
If TextBox4.Text.Contains(x.Key) Then
TextBox3.Text = x.Value
Else
If TextBox4.Text <> x.Key Then
MessageBox.Show("error")
End If
End If
Next
End Sub
You probably only need to stop the For Each loop when you were successful in your search. Add a Exit For after TextBox3.Text = x.Value. Since you found the address there's no need to look further.

Execute sql query from tab click event

I have a project where I am connecting my database to the windows application in vb.net. I am required to make tabs that sort the data in a specific way. For example, it is a student database with names, etc. So When I press the "Student by Last name" tab, it sorts the data by last name in ascending order. So, I made a query which brought a button, but I don't know how to execute the button automatically when the tab page is clicked. The user can't have the control of sorting. The tab does it itself. Any help will be great! I have been looking everywhere for help.
Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles tbLastName.Click
TabPage1.Hide() "this is made to get rid of previous page, but may be unnecessary"
tbLastName.Show() "this is supposed to show the data"
Sort_By_LastNameToolStripButton.Enabled() "My attempt to execute code from the query button that I made hidden"
End Sub
Try the tab control Selected event to run your database code
Keep a copy of the queried data, and then order it depending on which tab is selected. Use the TabControl.SelectedIndexChanged event
Private queryData As IEnumerable(Of Student)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
queryData = QueryStudentsFromDatabase()
End Sub
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
Select Case TabControl1.SelectedIndex
Case 0 ' Last Name
Dim displayData = queryData.OrderBy(Function(s) s.LastName)
Case 1 ' Student ID
Dim displayData = queryData.OrderBy(Function(s) s.ID)
End Select
ListView1.DataSource = displayData ' or whatever
End Sub
This is a very simple example. In the interest of brevity, it is performing work on the UI thread. You can handle offloading the work if you wish.

MessageBox appears at wrong time

I have a form which contains a PctureBox. When the user clicks this PictureBox, they will proceed to another form.
In the other form, I have a DataGridView and I have a search TextBox for the user to search content in the DataGridView. However I want to display "no record found" when the user enters something that is not in the database.
The MessageBox displays "no record found" however it also does this when the user first clicks on the PictureBox and the form loads.
Code:
Private Sub TextBox3_TextChanged_1(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
If Me.MasterlistTableAdapter1.FillBySearchProject(Me.DocumentDataSet.masterlist, TextBox3.Text)=0 Then
System.Windows.Forms.MessageBox.Show("No Record has been Found")
End If
End Sub
When I created a Button this code works perfectly. The prompt only displays when no records are found on the search.
I don't want to use a Button to do the search. My search functions when a user only types several words, data found.
Try this
Private Sub TextBox3_TextChanged_1(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
If Not TextBox3.Text = "" Then
If Me.MasterlistTableAdapter1.FillBySearchProject(Me.DocumentDataSet.masterlist, TextBox3.Text)=0 Then
System.Windows.Forms.MessageBox.Show("No Record has been Found")
End If
End If
End Sub

vb.net add values from listbox to textbox via drag&drop AND via double click

I'm struggling with some functionality I want to use on my Windows form.
( Just for info, this is for an AutoDesk Inventor AddIn. )
This is my form layout.
The current workflow
The top 4 list-boxes are filled with available parameter names. The user chooses the parameter(s) he/she wants to use and drags and drops it into one of the driving parameter text-boxes ( marked with the <1> label ).
The code that relates to the drag and drop operations
Private Sub lstTemp_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles lbModelParameters.MouseDown,
lbUserParameters.MouseDown,
lbReferenceParameters.MouseDown,
lbLinkedParameters.MouseDown
' In order to access a specific item in a listbox.itemcollection, you must think of it
' as an array of data or a collection and access it in the same manner by always
' letting VB know which item you intend to use by identifying it with its index location
' within the collection. And this is better than taking up basket weaving :-)
lbModelParameters.DoDragDrop(sender.Items(sender.SelectedIndex()).ToString, DragDropEffects.Move)
End Sub
Private Sub txtTemp_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragEnter,
tbParameter2.DragEnter,
tbParameter3.DragEnter,
tbParameter4.DragEnter,
tbParameter5.DragEnter
'Check the format of the incoming data and accept it if the destination control is able to handle
' the data format
'Data verification
If e.Data().GetDataPresent(DataFormats.Text) Then
e.Effect() = DragDropEffects.Move
Else
e.Effect() = DragDropEffects.None
End If
End Sub
Private Sub txtTemp_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragDrop,
tbParameter2.DragDrop,
tbParameter3.DragDrop,
tbParameter4.DragDrop,
tbParameter5.DragDrop
'This procedure receives the dragged data once it passes the data verification handled by the DragEnter method
'Drops the data onto the destination control
sender.Text() = e.Data().GetData(DataFormats.Text).ToString()
End Sub
New functionality
Now I would like to decrease the user mouse movement for ergonomic reasons and speed. But I would also like to keep to the drag and drop functionality. As it can overwrite a value that has already been added by the user.
I would like to be able to DoubleClick a item in the listbox, and that item should be added to the first empty textbox. I named my textboxes with a number so it's easy to loop over them all to check if it's empty.
I tried doing it with this code, but my double click event never gets fired. It always goes to the drag and drop. How do you do handle this, that the double click gets fired instead of drag drop?
Private Sub ParameterAddDoubleClick(sender As Object, e As EventArgs) _
Handles lbModelParameters.DoubleClick,
lbUserParameters.DoubleClick,
lbReferenceParameters.DoubleClick,
lbLinkedParameters.DoubleClick
Dim oControl As Windows.Forms.ListBox
oControl = DirectCast(sender, Windows.Forms.ListBox)
' Add line in likedparameters listbox
If oControl.SelectedIndex <> -1 Then
' Loop trough all the controls to see if one is empty
' if it's empty add parameter, else go to next
' if all textboxes are used do nothing.
For i = 1 To 6
Dim oTextbox As Windows.Forms.TextBox =
CType(gbDrivingParameters.Controls("tbParameter" & i),
Windows.Forms.TextBox)
If oTextbox.TextLength = 0 Then
' Add the sender item into the linked listbox
oTextbox.Text = oControl.Items.Item(oControl.SelectedIndex)
End If
Next
End If
End Sub
I hope my question is clear, and well prepared. If there is additional information needed, please let me know in a comment.
Mousedown triggers the DoDragDrop, wich stops the doubleclick-event from firing.
To identify if a user doubleclicks or wants to perform a dragdrop, consider the following:
Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
' Determine whether we are performing a drag operation OR a double click
If e.Clicks = 1 Then
TextBox1.Text = "mousedown"
Else
TextBox1.Text = "dblclick"
End If
End Sub

Labels & Text wont update accordingly

I developed an application which is like a digital comprehension sheet activity.
The order of which this works is:
A user double clicks an underscored text area on a text box
A form opens which asks them to place an answer
The answer is validated, if true it goes back to the original form
The issue here is that for some odd reason my labels don't update on step 3, as- well as the text. I have a label named lbAnswerStatus which notifies the user if they have a correct answer, the text does not update, and the 'SelectedText' on Form 1 should be replaced with the answer (if correct)
Here is my code:
Form 1 (when textbox is clicked):
Form2.Answer(answers(counter))
answers(counter) represents the correct answer being passed on, to compare with users answer in form 2
Form 2:
If tbAnswer.Text = theanswer Then
Form1.answerStatus(True, theanswer)
Form 1:
Public Sub answerStatus(status, answer)
If status = true Then
Form2.Close()
rtb.SelectedText = answer
lbAnswerStatus.ForeColor = Color.Green
End If
End Sub
My first assumption was that the Rich text box's SelectedText wasn't changing because it didn't have focus on it however, the lbAnswerStatus color didn't change either, so I figured that there was issues with making modifications to the form.
I used a message box to test whether lbAnswerStatus.Text would pop up and it did, so it can read but not write.
I also attempted to change the text of the label and selectedtext of the textbox in step 1 and it worked fine.
Any ideas what may be causing this issue?
Thanks.
I guess that you want your Form2 (AnswerForm) presented as a modal dialog. Doing that, you can return a result. You didn't say what you want to happen to the answer status label or the answer form if the supplied answer is incorrect.
Just as an example of how it can be done, create a new Windows Forms project. On Form1, place a button (Button1) and a label ("lblAnswerStatus"). Add a new form named "AnswerForm" to the project, and add a TextBox ("TextBox1") and a button ("bnDone").
As code for AnswerForm:
Public Class AnswerForm
Private statusLabel As Label
Private answerText As String
Private Sub bnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnDone.Click
If TextBox1.Text.Equals(answerText, StringComparison.CurrentCultureIgnoreCase) Then
' Alternative 1: set the color here if you want to
statusLabel.ForeColor = Color.Green
' return a value indicating success
Me.DialogResult = Windows.Forms.DialogResult.Yes
Me.Close()
Else
' indicate error
statusLabel.ForeColor = Color.Red
End If
End Sub
Public Sub New(ByVal statusLabel As Label, ByVal answerText As String)
InitializeComponent()
Me.statusLabel = statusLabel
Me.answerText = answerText
End Sub
End Class
and as code for Form1:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
lblAnswerStatus.ForeColor = Color.Blue
Using answerFrm As New AnswerForm(lblAnswerStatus, "X")
Dim dlgResult = answerFrm.ShowDialog()
' Alternative 2: use this if you want to change the color in this handler
If dlgResult = DialogResult.Yes Then
lblAnswerStatus.ForeColor = Color.Purple
End If
End Using
End Sub
End Class
If you click Button1 on Form1, a dialog box appears. Type into its TextBox1 and click bnDone. Because the instance of AnswerForm has a reference to lblAnswerStatus (supplied in its constructor), it is easy to update the latter, e.g. it turns red if you enter the wrong answer.