VB.Net How to close random choosed form - vb.net

I am making some kind of quiz. I have made randomizer for questions. So when one question(form) pops up and when I click the right answer new form pops up, where you have one label and button to continue. I have made that when I click continue button next question(form) pops up, but i want that the previous form closes too, but i dont know how to name it or what to do.
Dim rn As New Random
TextBox1.Text = rn.Next(1, 4)
If TextBox1.Text = 1 Then
Form4.Show()
Form4.Timer1.Start()
End If
If TextBox1.Text = 2 Then
Form7.Show()
Form7.Timer1.Start()
End If
If TextBox1.Text = 3 Then
Form8.Show()
Form8.Timer1.Start()
End If
If TextBox1.Text = 4 Then
Form12.Show()
Form12.Timer1.Start()
End If

Hand over a reference to the question to the result form. Then you can call the Close() method on the previous question before opening the next one.

How about a routine that closes all your forms before opening a new one.
This isn't the best way - as your telling the forms to close even if they weren't open.
But it will do what you are asking.
Here is an example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rn As New Random
Dim randomForm As UInteger = rn.Next(1, 3) 'Random Form Number
TextBox1.Text = randomForm 'Store the Random Number here
closeQuestionForms() 'Routine called before opening others
Select Case randomForm
Case 1
Form2.Show()
'Do something else here
Case 2
Form3.Show()
End Select
End Sub
Private Sub closeQuestionForms() 'Closes the forms
Form2.Close()
Form3.Close()
MessageBox.Show("Closed Question Forms")
End Sub
Again, There is probably a better way which other answers might show you. But this way should work fine.

Related

Checkboxlist applying If statements

I am stating VB and since it is so close to VBScript I have been having fun with it. But now I have come across the "Checkboxlist".
My boss saw me making a Windows Forms Application and asked me to make him a interface (GUI) for one of his batch files. In the batch you start by choosing between lines 1 through 10 and it does the rest. So I made a Checkboxlist and made check-boxes going from 1 to 10. Now I am not sure how to tell it that when I click a button a if statement looks at what has been checked and take to appropriate action.
I think i am suppose to start with something like
If CheckedListBox1.Items() = True then
But i know this does not work.
Anything thing will help.
Thank you.
It sounds like you're looking for the ItemCheck event. This event is fired when the checked state of an item changes.
Private Sub HandleCheckedListBox1ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim item As Object = Me.CheckedListBox1.Items.Item(e.Index)
Dim text As String = Me.CheckedListBox1.GetItemText(item)
Select Case e.CurrentValue
Case CheckState.Unchecked
'...
Case CheckState.Checked
'...
Case CheckState.Indeterminate
'...
End Select
End Sub
Or iterate all checked items:
Private Sub HandleButton1Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each item As Object In Me.CheckedListBox1.CheckedItems
Dim text As String = Me.CheckedListBox1.GetItemText(item)
'...
Next
End Sub

Data doesn't display when working with multiple forms

I'm new to VB.NET and have been struggling all afternoon with something. I've found similar questions on the forum but none of them seemed to describe my problem exactly. I'm fairly sure that I'm missing something very basic.
I have made a main form which currently holds only one button which purpose is to open up a second form and close the main form. Based on the settings the user will select on the 2nd form the first form might have to be adapted to match with the new settings. But the problem occurs even before that.
The 'settings' form has 15 textboxes which I drew onto the form in development mode. They are called ID1, ID2,..,ID15. The values which I want to display in there are saved in an array:
Dim ids(15) as integer
Next, I created a module to simulate what you could call a control array as I used to use them in VB6.
Public sources() As TextBox = [frmSettings.ID1, frmSettings.ID2, //and so on
I did this to be able to iterate through all the 15 textboxes:
For i = 0 To 14
Sources(i).Text = ids(i + 1)
Next
Then I added on the main form this code to the Button1_Click() event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frmSettings.Show()
Me.Close()
End Sub
I did the same thing for the 'exit ' button on the frmSettings form.
This seems to work, but only once. I launch the application, push the button and frmSettings pops up and shows all the values from the array in the textboxes. When I push the 'close' button, I return to the main page.
So far so good, but if I try to return to frmSettings a second time, all the textboxes remain blank as if the code I added to the form never gets executed.
Any help would be greatly appreciated!
First, make sure the array that holds your data is accessible to both forms:
Module Module1
Public ids(15) As Integer
End Module
There should not be a declaration for "ids" in either form.
Next, make frmSettings itself responsible for loading and saving the data:
Public Class frmSettings
Private Sub frmSettings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches() As Control
For i As Integer = 0 To 14
matches = Me.Controls.Find("ID" & (i + 1), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim TB As TextBox = DirectCast(matches(0), TextBox)
TB.Text = ids(i)
End If
Next
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim valid As Boolean = True
Dim matches() As Control
For i As Integer = 0 To 14
matches = Me.Controls.Find("ID" & (i + 1), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim TB As TextBox = DirectCast(matches(0), TextBox)
Dim value As Integer
If Integer.TryParse(TB.Text, value) Then
ids(i) = value
Else
MessageBox.Show(TB.Name & ": " & TB.Text, "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Warning)
valid = False
End If
End If
Next
If valid Then
Me.Close()
End If
End Sub
End Class

VB 2013 Comparisons between user input and application memory

I've got two questions.
Firstly how would you compare for examble "My.Settings.ListBox1" of type "System. Collections. Specialized. StringCollection" to the content of "ListBox1"?
I have a number of items on my form (ListBoxes, Checkboxes and TextBoxes) for which the user can input data and I have created a menu item called save to which they can save the data to application memory so that when the form reloads the user doesn't need to inpuit the data.
That being said I would like to compare the latest user input to what is in memory so that when the user tries to exit the program, if they haven't hit save and the input doesn't match memory then a flag is raised and I can ask them whether they'd like to save or not.
But I'm stumped on this comparison if anybody can help?
Second question is about what I want to do with the comparisons. For each comparison I thought I could increment a counter, so that if all the comparisons aren't met and the counter is less than the maximum number then I can raise a flag and the user can be prompted to save. Much in the fashion:
Dim saved As Integer
saved = 0
If My.Settings.TextBox2 = TextBox2.Text Then saved = saved + 1
If My.Settings.TextBox5 = TextBox5.Text Then saved = saved + 1
If My.Settings.TextBox9 = TextBox9.Text Then saved = saved + 1
If saved = 3 Then Me.Close()
Else
*Then I will deal with the prompts at this point.
I've not tested this. Just a last minute thought before bed. But my question is, is there a more eloquent way of doing this? I'm sure there is. But this is the best my newbie VB brain could come up with at this hour.
Thanks for any help and suggestions!
If you want to check if the textboxes didn't change you could do it like this.
Just start at textbox 1 if that's true then check textbox 2 , then 3 and so on.
As soon 1 is not true you can ask the user if he wants to save.
Put in the Public Sub SaveTextBox() everything you want to save.
I just used a button for it ,but of course you need to use it in the closing event.
Maybe this is not the best way but it works.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = My.Settings.TextBox1
TextBox2.Text = My.Settings.TextBox2
TextBox3.Text = My.Settings.TextBox3
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If My.Settings.TextBox1 = TextBox1.Text Then
If My.Settings.TextBox2 = TextBox2.Text Then
If My.Settings.TextBox3 = TextBox3.Text Then
Me.Close()
Else
SaveTextBox()
End If
Else
SaveTextBox()
End If
Else
SaveTextBox()
End If
End Sub
Public Sub SaveTextBox()
If MessageBox.Show("Save new settings ?", "My Application", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question) _
= DialogResult.Yes Then
My.Settings.TextBox1 = TextBox1.Text
My.Settings.TextBox2 = TextBox2.Text
My.Settings.TextBox3 = TextBox3.Text
My.Settings.Save()
Me.Close()
Else
Me.Close()
End If
End Sub

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

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

VB.NET Form Hiding Issue

I have a custom form, B. B is created by A, which has a handle to B.VisibleChanged.
B only has an OK and Cancel button on it, and I want to do some logic when OK is hit.
B's OK button is dealt with like this:
Me.Result = Windows.Forms.DialogResult.OK
Me.Hide()
The code in A is properly hit and run, but it never hides B. When I check the values of the properties on B, it shows me Visible = False.
Does anyone have any suggestions as to the possible cause of this issue?
Edit
This form was shown using the Show() command, as I'm making a later call to have the form flash using FlashWindow().
Not exactly sure about your question.
why not use me.Close() instead of me.Hide?
Is it OK to have multiple instances of B at a time? If not, go for ShowDialog.
If you can rephrase the question, someone can probably resolve your problem.
I suppose you want to display a messagebox with an ok & cancel button. Instead of using a form use a mesagebox.
eg:
DialogResult dgResult = MessageBox.Show("Click Yes or No", "Test App", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (DialogResult.OK == dgResult)
{
//Do what you want.
}
else
{
//Do nothing.
}
If you are going to use a form, to do that & wanted to modify the parent's form, it would be advisable to use delegates to prevent form B from modifying form A's variables.
Else: (Not recommended)
Declare form B as a member variable of form A.
when required instantiate form B.
do B.ShowDialog();
internally in OK & cancel do this.dispose();
Again when you need form B just instantiate. re - instantiation will not be too much of an overhead if you dont call it very often.
But if you only need OK Cancel, use message box instead.
The show/hide approach works for me:
Public Class frmViewChild ' your form A
Private WithEvents _edit As frmEdit
'code
Private Sub editCell()
Dim PKVal As String
Dim PKVal2 As String
Dim fieldOrdinalPos As Integer
Dim isLastField As Boolean
If _edit Is Nothing Then
_edit = New frmEdit
_edit.MdiParent = Me.MdiParent
End If
'code
_edit.init(<params>)
If Not _edit.isNothing Then
_edit.Show()
_edit.WindowState = FormWindowState.Maximized
_edit.BringToFront()
End If
End Sub
'code
Private Sub _edit_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles _edit.VisibleChanged
If Not _edit.Visible Then
WindowState = FormWindowState.Maximized ' revert after closing edit form
End If
End Sub
Public Class frmEdit ' your form B
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim ret As Integer
doOK(ret)
If ret > -1 Then ' no error
Me.Hide() ' close form, but didn't cancel
End If
End Sub
HTH