Remove the windows form controls on exit - vb.net

I'm adding the form controls on loading the form manually:
Me.FieldI = New TextBox()
Me.FieldI.Location = New System.Drawing.Point(50, 10)
Me.FieldI.Name = "FieldI"
Me.FieldI.Size = New System.Drawing.Size(40, 20)
Me.FieldI.TabIndex = 5
Me.Conversion.Controls.Add(Me.FieldI)
[..]
When I close the form window and reopen it, the control is still there (with the old .Text content , because its an textbox in this case).
I would like to remove the controls that have been created while form loading on the form close event, to prevent doubling the elements on my form.
How can I achieve this?
edit
Form closing code looks following (just showing up the main form back):
Private Sub Form1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosing
Main.Show()
End Sub

The problem here is that the form is not being disposed, so when you open it again the controls are still there from the last time it was opened.
Try the following:
Using frm = New subForm()
frm.ShowDialog()
End Using
The variable frm will be disposed after the using.
Also...
You can also provide feedback from a dialog, to check whether the form was successful or not. For example:
Dim frm As New subForm()
If frm.ShowDialog = DialogResult.OK Then
'YAY!
Else
'Something failed
End If

Related

Parent form sometimes does not close (Only in Windows 10)

My main form is frmInvoice. This sub is located inside frmInvoice.
This is one of the Subs that sometimes causes frmDark to not close. frmLookup does not display when this happens. frmDark just stays there covering frmInvoice. It's like it doesn't reach the call to frm.ShowDialog(frmDark), cause when I press the lookup key, it displays the frmLookup, but upon closing frmLookup, frmDark is still there.
No exception is being raised.
Note that this only happens in Windows 10. In Windows 8/7, this never happened. What am I missing?
This happens at different times. Sometimes I could press the lookup key for 20 times and it will display fine. Sometimes, after 1 press of the lookup key and this happens.
Private Sub ItemLookup()
Try
Using frmDark As New Form
With frmDark
.ShowInTaskbar = False
.Icon = Me.Icon
.FormBorderStyle = Windows.Forms.FormBorderStyle.None
.BackColor = Color.Black
.Opacity = 0.95
.WindowState = FormWindowState.Maximized
.Show(Me)
Using frm As New frmLookup
With frm
.Icon = Me.Icon
.ShowDialog(frmDark)
frmDark.Close()
If .DialogResult = Windows.Forms.DialogResult.OK Then
' Do stuff here
End If
End With
End Using
End With
End Using
Catch ex As Exception
ErrMsg(ex)
End Try
End Sub
UPDATE: I'm using .Net Framework 4.8
Thanks
I would suggest rearranging the code like so:
Dim lookupResult As DialogResult
Using frmDark As New Form With {.ShowInTaskbar = False,
.Icon = Me.Icon,
...}
frmDark.Show(Me)
Using frm As New frmLookup With {.Icon = Me.Icon}
lookupResult = frm.ShowDialog(frmDark)
End Using
End Using
If lookupResult = DialogResult.OK Then
'...
End If
Because that code exits the Using block that created frmDark, there should be no way that it can't close.
Also, instead of using a vanilla Form and configuring it on demand, I would suggest that you create a dedicated form type to use as the overlay in that scenario. You can then get rid of all the property assignments.
Having a dedicated overlay form would also allow you to reconfigure things significantly and, in my opinion, better. The overlay form could have a property of type Form. You main form could then create a frmLookup instance and assign it to that property, than call ShowDialog on the overlay form. In the Shown event handler of the overlay form, it could then call ShowDialog on the form in that property. When that call returns, it could assign the result to its own DialogResult property and close itself. The main form would then just get the result from calling ShowDialog on the overlay. That might look like this:
Public Class OverlayForm
Public Property DialogueForm As Form
Private Sub OverlayForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
DialogResult = DialogueForm.ShowDialog()
End Sub
End Class
and this:
Public Class MainForm
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using dialogue As New DialogueForm,
overlay As New OverlayForm With {.DialogueForm = dialogue}
If overlay.ShowDialog() = DialogResult.OK Then
MessageBox.Show("OK")
End If
End Using
End Sub
End Class

frm.showDialog dispose when openFileDialog close [vb.net]

I have two forms. First form is used to display a set of record and second form is used to edit the particular record. I called the second form using frm.ShowDialog(). Inside that form I got a button to call the OpenFileDialog. When I press OK or Cancel, then the second form dispose together with the OpenFileDialog. I'm pretty should that my code is correct, but it was the ShowDialog() problem. Anyone have idea on this issue?
This is how i called the second form from the first form to display the Information.
Private Sub btnViewOrganizationEdit_Click(sender As Object, e As EventArgs) Handles btnViewOrganizationEdit.Click, dgvOrganization.DoubleClick
Dim selectedOrganization As New Organization
'check permission because double click
If dgvOrganization.RowCount > 0 Then
strOrganizationID = dgvOrganization.SelectedRows.Item(0).Cells(0).Value
selectedOrganization = helperOrganizationCKJ.getOrganizationByID(strOrganizationID)
frmEditOrganizationCKJ.objOrganization = selectedOrganization
frmEditOrganizationCKJ.ShowDialog()
iniGridView()
End If
End Sub
This is how i called the OpenFileDialog.
Private Sub btnEditOrganizationImage_Click(sender As Object, e As EventArgs) Handles btnEditOrganizationImage.Click
dlgImage.Filter = ""
Dim codecs() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()
Dim sep As String = String.Empty
For Each c As ImageCodecInfo In codecs
Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
dlgImage.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlgImage.Filter, sep, codecName, c.FilenameExtension)
sep = "|"
Next
dlgImage.FilterIndex = 5
If dlgImage.ShowDialog(Me) = DialogResult.OK Then
'Get the image name
Dim img = dlgImage.FileName
picEditOrganizationImage.Image = System.Drawing.Bitmap.FromFile(img)
End If
End Sub
The frmEditOrganizationCKJ just dispose together with the dispose of OpenFileDialog.
Probably you have copy/pasted your btnEditOrganizationImage from a button that has the DialogResult property set to something different than DialogResult.None.
This triggers the closing action for your modal form and the fix is really simple.
Set the property DialogResult for the btnEditOrganizationImage to DialogResult.None
From MSDN on Button.DialogResult
If the DialogResult for this property is set to anything other than
None, and if the parent form was displayed through the ShowDialog
method, clicking the button closes the parent form without your having
to hook up any events. The form's DialogResult property is then set to
the DialogResult of the button when the button is clicked

Form Enabled in FormClosing Event Not Working

I'll show you my code first:
Private Sub AddProductToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddProductToolStripMenuItem.Click
Me.Enabled = False
Dim frmAddProduct As New FormAddProduct
frmAddProduct.Show()
frmAddProduct.Owner = Me
End Sub
That is my Main Form to call AddProduct form, and this is my FormClosing in AddProduct
Private Sub FormAddProduct_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
ButtonReset.PerformClick()
Lock()
Me.Owner = Nothing
Me.Hide()
Dim frmMainIndex As New FormMainIndex
frmMainIndex.Enabled = True
End Sub
So I have set enabled = false in my main form when it call Add Product form, and enabled = true when I close my Add Product form, but enabled = true won't work.
When I close my Add Product, it's only hide Add Product form but not enabling main form, main form still not enabled. Is there something wrong with my code?
This line is your problem:
Dim frmMainIndex As New FormMainIndex
You are instantiating a new FormMainIndex. Whenever you use the New keyword you are creating a completely new and independant object. frmMainIndex is a completely different form than the first one which opened your FormAddProduct form.
Since you've set the FormAddProduct's owner to your FormMainIndex form, just set the owner's Enabled property to True instead:
ButtonReset.PerformClick()
Lock()
Me.Owner.Enabled = True
Me.Owner = Nothing
Me.Hide()
Also, your Me.Hide() call doesn't make any sense since your form is about to be closed.
Because you created a new instance of FormMainIndex, the frmMainIndex.Enabled was applied to this new instance, not the one that created your FormAddProduct. Why don't you show your FormAddProduct as a dialog. like this
Dim frmAddProduct As New FormAddProduct
frmAddProduct.ShowDialog(Me)

Winforms - MDI Parent refresh/re-activate

I have a MDI Parent form which has a menustrip for the application. My application startup file is the MDI Parent form which on load calls a child login form. Code as below:
Dim myForm As Form = New Login
Dim formResult As DialogResult = myForm.ShowDialog()
If formResult = Windows.Forms.DialogResult.OK Then
If LoginSucceeded = True Then
Me.tabMainMenu.Visible = True
ApplyUserAccess(eApp.DataAccess.DAL_UserSettings.SelectMenuSettingByUserID(glbUserID))
myForm.Dispose()
End If
End If
The menustrip has a Logout label which when clicked disables the menu strip and displays the login form again.
The boolean field LoginSucceeded determines a successful validation of the user credentials and sets the menu according to the access given to that user. My problem is the first time the main menu on the MDI parent is set properly based on the user's access. After logging out and logging in again, i wanted to set the main menu accordingly again which is not happening.
The Form_Load event on the MDI Parent is being executed only once.
Any tips of re-painting the MDI parent when it receives focus the 2nd time onwards.
Thanks,
ZK
My code for the Logoff is as below:
Dim blnLogout As DialogResult = MessageBox.Show("Are You Sure You Want To Logout?", "eApp", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If blnLogout = Windows.Forms.DialogResult.Yes Then
SetToolbarMenuStyle()
tabMainMenu.Visible = False
LoginSucceeded = False
blnShowLoginTab = True
Dim myForm As Form = New Login
myForm.MdiParent = Me
myForm.WindowState = FormWindowState.Normal
myForm.Show()
End If
Move your login code to its own method in your main form so you can call it multiple times:
Public Class Form1
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown ValidateLogin()
ValidateLogin()
End Sub
Private Sub LoginLogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoginLogoutToolStripMenuItem.Click
ValidateLogin()
End Sub
Private Sub ValidateLogin()
' disable appropriate main form elements so they can't access anything:
Me.tabMainMenu.Visible = False
Using myForm As New Login
If myForm.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
' login succeeded: re-enable main form elements
Me.tabMainMenu.Visible = True
ApplyUserAccess(eApp.DataAccess.DAL_UserSettings.SelectMenuSettingByUserID(glbUserID))
Else
MessageBox.Show("Login Failed")
End If
End Using
End Sub
End Class
You also don't need the "LoginSucceeded" variable. You can pass a success/failure back to the main form by setting DialogResult to OK in your Login form:
Public Class Login
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If True Then ' <-- perform your check
Me.DialogResult = Windows.Forms.DialogResult.OK ' only return OK if login has succeeded
End If
End Sub
End Class
Here are presumptions on your code, I'm guessing you added the code about on the Form.Load event. The Form.Load event only gets raised when the form is shown for the first time.
According to MSDN
Form.Load Event
Occurs before a form is displayed for the first time.
And now, when you Log-Off, you're setting the visibility of the form to false. So what I suggest is you move your code from the Form.Load event to the Form.VisibleChanged event.
According to MSDN
Form.Load Event
Occurs when the Visible property value changes.

How to refresh a DataGridView when a dialog form is closed

I am trying to refresh a datagirdview when i add a new record using a dialog form. I would like to know how can i refresh my datagirdview. I have two Win Forms . Form A is called FrmContactDetailList which is having a datagridview which i is showing data from sql server. Below first block of code is used to bind data to the grid. which is given in form load event and also in this form i have a Button called "Add New Record" . Once i press this button its opening a win form which is opening another form. Below is that code which i used to open this in by button click event.
This will open Form B. Form is called FrmClientDetails. This form will have a text box and a save button . So once i enter the new name in the text box and press save i want the datagirdview which is in Form A to be updated . and show the new record once i close Form B. how can i achieve this.
This Code is used to bind the datagridview. I have given this is the form load event.
Sub GetContactList()
Dim BindData As New VoucherClass
Dim dt As DataTable = BindData .Get_Client_List
DataGridView.DataSource = dt
End Sub
Private Sub FrmContactDetailsList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetContactList()
End Sub
I have using this code to open the dialog form to enter the new data.
Private Sub BtnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOpen.Click
Dim FrmNewContact As New FrmClientDetails
FrmNewContact.Owner = Me
FrmNewContact.ShowDialog()
End Sub
When the binding data change it is automatically reflected to the data grid view that is bond.
Edit:
Handle the FrmNewContact's Closing event. You can refresh your datagridview in that sub.
Dim WithEvents dialog As New FrmNewContact
Sub done() Handles dialog.FormClosed
Me.DataGridView1.Refresh()
End Sub
Next edit:
Dim BindData As New VoucherClass
Dim dt As DataTable = BindData .Get_Client_List
Declare them outside of the sub. So you should have this:
Dim BindData as VoucherClass
Dim dt as DataTable
Sub GetContactList()
BindData = New VoucherClass
dt = BindData .Get_Client_List
DataGridView.DataSource = dt
End Sub
Try this: Instead of FrmNewContact.ShowDialog() If FrmNewContact.ShowDialog() = DialogResult.OK Then Me.DataFridView.Refresh() End IF You may need to include a setter for your dialog result at the close action for your modal. Me.DialogResult = DialogResult.OK Me.Close()