|
-
Feb 25th, 2013, 10:17 PM
#1
Thread Starter
Fanatic Member
[RESOLVED] Passing variables from form to form
I've been searching hours to figure this out.
I need to pass the value of a textbox (FirstNametextbox) to a variable then use this variable in another form.
I used to be able to do a Textbox1.text = form1.textbox.text but that doesn't work. I've tried setting up a public var in Form1: Public Var1 as string = FirstNametextbox.text. then on form2 using it like textbox1 = var1. That didn't work either. Tried a buch of other stuff I found around the net but still no dice so I'm here.
Code:
oDoc.Unprotect()
oDoc.Bookmarks("t1").Range.Text = Projects.FirstNameTextBox.text ''''<-------this is where I need the variable passed to. Projects is the other Form name
oDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields)
this is a partial code but I think you can tell where I need to place the variable
Any help PLEASE
Life is about making some things happen, not waiting around for something to happen.
-
Feb 25th, 2013, 10:49 PM
#2
Re: Passing variables from form to form
Here I am making a few assumptions:
- You have two forms, form1 and form2
- You have two textbox. One on each form. Both named textbox1
- You have three buttons. Two on form1 and one on form2.
You will declare a public variable in form1. Set the public variable in form2. Then display the contents of that variable. Here is form1:
Code:
Option Strict On
Option Explicit On
Public Class Form1
Public var As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Form2.Show()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
TextBox1.Text = var
End Sub
End Class
and here is form2:
Code:
Option Strict On
Option Explicit On
Public Class Form2
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Form1.var = TextBox1.Text
End Sub
End Class
-
Feb 26th, 2013, 12:20 AM
#3
Lively Member
Re: Passing variables from form to form
I would add a module to declare public variable that would be used across all the forms in the project. I think this makes everything easier..
-
Feb 26th, 2013, 12:57 AM
#4
Re: Passing variables from form to form
Hi,
Another way to pass information between Forms, without having to resort to Globally declared variables, is to create a Constructor in the second form and then pass a value to the second form via that constructor when declaring a variable of that form type. Have a look at this example:-
Form 1:-
Code:
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim mySecondForm As New Form2(TextBox1.Text)
mySecondForm.ShowDialog()
End Sub
End Class
Form 2:-
Code:
Public Class Form2
Private strMyPassedTextString As String
Public Sub New(ByVal strValue As String)
InitializeComponent()
strMyPassedTextString = strValue
End Sub
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
MsgBox(strMyPassedTextString)
End Sub
End Class
Hope that helps.
Cheers,
Ian
-
Feb 26th, 2013, 01:27 AM
#5
Junior Member
Re: Passing variables from form to form
for now, it's the best way, unless we can make textbox on form1 became public
-
Feb 26th, 2013, 09:34 AM
#6
Re: Passing variables from form to form
The textbox on Form1 is public be default. The problem is getting the specific instance of Form1 that is being shown.
Since the OP just said that "it didn't work" without explaining what happened, we are all guessing as to what they did. My guess is that the OP is not using default instances, which I feel is a good thing, but may or may not know what default instances are.
In any case, here's a whole thread on the subject of passing data between forms:
http://www.vbforums.com/search.php?searchid=683561
My usual boring signature: Nothing
 
-
Feb 26th, 2013, 12:29 PM
#7
Re: Passing variables from form to form
 Originally Posted by Shaggy Hiker
FYI - Link returns no matches.
-
Feb 26th, 2013, 02:45 PM
#8
Thread Starter
Fanatic Member
Re: Passing variables from form to form
my apologizes for not explaining what I was trying to do and the errors.
I have several forms, but working with only 2 in this case.
Form1 ("Projects") has several controls on it.
Form2 ("ReportEditor") has a listbox that holds a list of reports
In form2 I click a report name and the corresponding (MS Word)report opens. Now what I want to do is take the text property from the textbox on Form1 and insert them into my report. Getting them into a bookmark is not the issue, it's getting the text property across forms via a variable or directly I guess.
But I see another problem I'm unsure about now. This is a data bound application so, Form1's controls are filled just by a bindingsource.filter method (see code)
Code:
Sub New(ByVal ds As ERVDataSet, ByVal id As Integer)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.ProjectsBindingSource.DataSource = ds
Me.ProjectsBindingSource.Filter = "ProjectID = " & id.ToString
End Sub
Now in Form1 I have:
Code:
Public Property CustomerName() As String
Get
Return FirstNameTextBox.Text
End Get
Set(ByVal Value As String)
FirstNameTextBox.Text = Value
End Set
End Property
and in Form2 I have:
Code:
Private Sub TreeView1_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
' only proceed if the node represents a file
If e.Node.ImageKey = "folder" Then Exit Sub
If e.Node.Tag Is "" Then Exit Sub
' try to open the file
Try
If e.Node.ImageKey = ".doc" Or e.Node.ImageKey = ".docx" Then
Dim oWord As Word.Application
Dim oDoc As Word.Document
' ''Start Word and open the document template.
oWord = CType(CreateObject("Word.Application"), Word.Application)
oDoc = oWord.Documents.Open(e.Node.Tag)
''Set the position of the Word App.
oDoc.Windows(1).WindowState = Word.WdWindowState.wdWindowStateNormal
oDoc.Windows(1).Application.Top = 52
oWord.Visible = True
Dim myfile As New File()
oDoc.Unprotect()
oDoc.Bookmarks("t1").Range.Text =
oDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields)
oWord = Nothing
oDoc = Nothing
End If
If e.Node.ImageKey = ".xls" Or e.Node.Tag Is ".xlsx" Then
'Keep the application object and the workbook object global, so you can
'retrieve the data in Button2_Click that was set in Button1_Click.
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet
' Create a new instance of Excel and start a new workbook.
objApp = New Excel.Application()
objBooks = objApp.Workbooks
objBook = objBooks.Open(CStr(e.Node.Tag))
objSheets = objBook.Worksheets
objSheet = CType(objSheets(1), Excel._Worksheet)
'Make it Visible to the user now that we are going to use it
objApp.Visible = True
''Set the position of the Excel App.
objApp.Windows(1).Application.WindowState = Excel.XlWindowState.xlNormal
objApp.Windows(1).WindowState = Excel.XlWindowState.xlMaximized
objApp.Windows(1).Application.Top = 55
'Make sure our object variable is destroyed and released since its going out of scope
objApp = Nothing
End If
Catch ex As Exception
MessageBox.Show("Error opening file: " & ex.Message)
End Try
End Sub
But im getting the error: Argument not specified for parameter 'ds' of 'Public Sub New(ds As ERVDataSet, id As Integer)'. for the Dim myfile As New File
I think this is due to setting ds as the id to get the proper record from the dataset????????????
So now how do I get that dynamic value in a new instance??????????
Last edited by crater; Feb 26th, 2013 at 02:58 PM.
Life is about making some things happen, not waiting around for something to happen.
-
Feb 26th, 2013, 02:53 PM
#9
Re: Passing variables from form to form
Oops, I posted the wrong URL. This is the right one:
http://www.vbforums.com/showthread.php?466253
My usual boring signature: Nothing
 
-
Feb 26th, 2013, 02:58 PM
#10
Re: Passing variables from form to form
Which line is giving you the error? It doesn't seem like it should be on the first line in red, but I'm not seeing anywhere else that looks likely, either.
My usual boring signature: Nothing
 
-
Feb 26th, 2013, 03:06 PM
#11
Re: Passing variables from form to form
If ...
Sub New(ByVal ds As ERVDataSet, ByVal id As Integer)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.ProjectsBindingSource.DataSource = ds
Me.ProjectsBindingSource.Filter = "ProjectID = " & id.ToString
End Sub
.... is part of the File class then ...
Dim myfile As New File()
... requires parameters for ds and id.
As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"
Reviews: "dunfiddlin likes his DataTables" - jmcilhinney
Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!
-
Feb 26th, 2013, 03:35 PM
#12
Frenzied Member
Re: Passing variables from form to form
 Originally Posted by Shaggy Hiker
Which line is giving you the error? It doesn't seem like it should be on the first line in red, but I'm not seeing anywhere else that looks likely, either.
Looks like he has a class File that he is trying to instantiate without the correct parameters being passed to it...
Sean
Some days when I think about the next 30 years or so of my life I am going to spend writing code, I happily contemplate stepping off a curb in front of a fast moving bus.
-
Feb 26th, 2013, 03:50 PM
#13
Thread Starter
Fanatic Member
Re: Passing variables from form to form
yes the class name is File, I changed the Class name (form name) because I also have a data table named Projects, so I thought that might me causing some confussion.
But how do I get the var. ds and id; Do I have to make public variables for them also?
@ shaggy, I read that thread, quite imformative but as a noob somewhat confusing just because I'm trying to do the inverse of what is explained there. ie Thread goes from Form1 to Form2 and reports back to Form1. I'm trying to go from Form1 to Form2 and into a report. so I'm side stepping part of it kindof. My interpertation of the thread is: open Form1, do something, open Form2, do some calculation in Form2 and report that value back to Form1. Is this correct?
Last edited by crater; Feb 26th, 2013 at 04:02 PM.
Life is about making some things happen, not waiting around for something to happen.
-
Feb 26th, 2013, 03:58 PM
#14
Frenzied Member
Re: Passing variables from form to form
 Originally Posted by crater
yes the class name is File, I changed the Class name (form name) because I also have a data table named Projects, so I thought that might me causing some confussion.
But how do I get the var. ds and id; Do I have to make public variables for them also?
Where are they defined? YOu are passing them into the constructor, but they have to be coming from somewhere you haven't posted in the code you've shown...
Sean
Some days when I think about the next 30 years or so of my life I am going to spend writing code, I happily contemplate stepping off a curb in front of a fast moving bus.
-
Feb 26th, 2013, 04:01 PM
#15
Re: Passing variables from form to form
Well yes. Otherwise what's the point of the Constructor? Presumably you had something in mind when you wrote ....
Sub New(ByVal ds As ERVDataSet, ByVal id As Integer) ?
You require a dataset and an integer. So obviously you need to pass an existing dataset and an existing integer in ..
Dim myfile As New File(SomeDataset, SomeInteger)
As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"
Reviews: "dunfiddlin likes his DataTables" - jmcilhinney
Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!
-
Feb 26th, 2013, 04:09 PM
#16
Thread Starter
Fanatic Member
Re: Passing variables from form to form
Code:
Private Sub ProjectsDataGridView_DoubleClick(sender As Object, e As System.EventArgs) Handles ProjectsDataGridView.DoubleClick
Me.ProjectsBindingSource.EndEdit()
If Me.ProjectsBindingSource.Position > -1 Then
'Get the current product row
Dim row As ERVDataSet.ProjectsRow
row = CType(CType(Me.ProjectsBindingSource.Current, DataRowView).Row, ERVDataSet.ProjectsRow)
'Open the product detail form passing the dataset and the product ID
Dim projects As New File(Me.ERVDataSet, row.ProjectID)
projects.Show()
End If
End Sub
Is where there defined or come from
Life is about making some things happen, not waiting around for something to happen.
-
Feb 26th, 2013, 04:14 PM
#17
Frenzied Member
Re: Passing variables from form to form
 Originally Posted by crater
Code:
Private Sub ProjectsDataGridView_DoubleClick(sender As Object, e As System.EventArgs) Handles ProjectsDataGridView.DoubleClick
Me.ProjectsBindingSource.EndEdit()
If Me.ProjectsBindingSource.Position > -1 Then
'Get the current product row
Dim row As ERVDataSet.ProjectsRow
row = CType(CType(Me.ProjectsBindingSource.Current, DataRowView).Row, ERVDataSet.ProjectsRow)
'Open the product detail form passing the dataset and the product ID
Dim projects As New File(Me.ERVDataSet, row.ProjectID)
projects.Show()
End If
End Sub
Is where there defined or come from
Is class file some type of Form? You seem to be showing barely related bits of code here.
Sean
Some days when I think about the next 30 years or so of my life I am going to spend writing code, I happily contemplate stepping off a curb in front of a fast moving bus.
-
Feb 26th, 2013, 04:30 PM
#18
Thread Starter
Fanatic Member
Re: Passing variables from form to form
Sorry here is the full code for this class
Code:
Option Explicit On
Option Strict On
Public Class Search
Private Sub ProjectsBindingNavigatorSaveItem_Click(sender As System.Object, e As System.EventArgs) Handles ProjectsBindingNavigatorSaveItem.Click
SaveData()
End Sub
Private Sub Search_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ERVDataSet.HousingFunctions' table. You can move, or remove it, as needed.
Me.HousingFunctionsTableAdapter.Fill(Me.ERVDataSet.HousingFunctions)
'TODO: This line of code loads data into the 'ERVDataSet.ArcClass' table. You can move, or remove it, as needed.
Me.ArcClassTableAdapter.Fill(Me.ERVDataSet.ArcClass)
'TODO: This line of code loads data into the 'ERVDataSet.FoundationMaterial' table. You can move, or remove it, as needed.
Me.FoundationMaterialTableAdapter.Fill(Me.ERVDataSet.FoundationMaterial)
'TODO: This line of code loads data into the 'ERVDataSet.RoofMaterial' table. You can move, or remove it, as needed.
Me.RoofMaterialTableAdapter.Fill(Me.ERVDataSet.RoofMaterial)
'TODO: This line of code loads data into the 'ERVDataSet.WallMaterial' table. You can move, or remove it, as needed.
Me.WallMaterialTableAdapter.Fill(Me.ERVDataSet.WallMaterial)
'TODO: This line of code loads data into the 'ERVDataDataSet.Projects' table. You can move, or remove it, as needed.
Me.ProjectsTableAdapter.FillByNotArchived(Me.ERVDataSet.Projects)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
AddClient.Show()
AddClient.MdiParent = Home
End Sub
Private Sub ArchivedCheckBox_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles ArchivedCheckbox.CheckedChanged
If ArchivedCheckbox.Checked = True Then
Me.ProjectsTableAdapter.Fill(Me.ERVDataSet.Projects)
ProjectsDataGridView.DataSource = ProjectsBindingSource
Else
Me.ProjectsTableAdapter.FillByNotArchived(Me.ERVDataSet.Projects)
End If
End Sub
Private Sub ProjectsDataGridView_DoubleClick(sender As Object, e As System.EventArgs) Handles ProjectsDataGridView.DoubleClick
Me.ProjectsBindingSource.EndEdit()
If Me.ProjectsBindingSource.Position > -1 Then
'Get the current product row
Dim row As ERVDataSet.ProjectsRow
row = CType(CType(Me.ProjectsBindingSource.Current, DataRowView).Row, ERVDataSet.ProjectsRow)
'Open the product detail form passing the dataset and the product ID
Dim projects As New File(Me.ERVDataSet, row.ProjectID)
projects.Show()
End If
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim SearchIn As String
Dim SearchFor As String
SearchFor = TextBox1.Text
SearchIn = CStr(ComboBox1.SelectedItem)
Select Case SearchIn
Case Is = "Street Name"
ProjectsBindingSource.Filter = String.Format("StreetName Like'" & SearchFor & "%'")
Case Is = "Last Name"
ProjectsBindingSource.Filter = String.Format("LastName Like'" & SearchFor & "%'")
Case Is = "File Number"
ProjectsBindingSource.Filter = String.Format("FileNo Like'" & SearchFor & "%'")
Case Is = "Street Number"
ProjectsBindingSource.Filter = String.Format("StreetNo Like'" & SearchFor & "%'")
Case Is = "First Name"
ProjectsBindingSource.Filter = String.Format("FirstName Like'" & SearchFor & "%'")
End Select
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.ProjectsTableAdapter.Fill(Me.ERVDataSet.Projects)
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
SaveData()
Me.Close()
End Sub
Private Sub Button2_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Button2.MouseDown
Button2.BackColor = Color.GreenYellow
End Sub
Public Sub SaveData()
Try
Me.Validate()
Me.ProjectsBindingSource.EndEdit()
Me.FoundationMaterialBindingSource.EndEdit()
Me.WallMaterialBindingSource.EndEdit()
Me.RoofMaterialBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.ERVDataSet)
Catch ex As Exception
MsgBox("Update failed")
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedItem Is "All" Then
ProjectsBindingSource.Filter = Nothing
End If
End Sub
End Class
and the next Class
Code:
Option Explicit On
Option Strict On
Public Class File
Public Property CustomerName() As String
Get
Return FirstNameTextBox.Text
End Get
Set(ByVal Value As String)
FirstNameTextBox.Text = Value
End Set
End Property
Sub New(ByVal ds As ERVDataSet, ByVal id As Integer)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.ProjectsBindingSource.DataSource = ds
Me.ProjectsBindingSource.Filter = "ProjectID = " & id.ToString
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
SaveData()
Me.Close()
End Sub
Private Sub Projects_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
SaveData()
End Sub
Private Sub Projects_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ERVDataSet.Setup' table. You can move, or remove it, as needed.
Me.SetupTableAdapter.Fill(Me.ERVDataSet.Setup)
'TODO: This line of code loads data into the 'ERVDataSet.Setup' table. You can move, or remove it, as needed.
Me.SetupTableAdapter.Fill(Me.ERVDataSet.Setup)
Me.MdiParent = Home
'TODO: This line of code loads data into the 'ERVDataSet.CurrentHousingFunction' table. You can move, or remove it, as needed.
Me.CurrentHousingFunctionTableAdapter.Fill(Me.ERVDataSet.CurrentHousingFunction)
'TODO: This line of code loads data into the 'ERVDataSet.ArcClass' table. You can move, or remove it, as needed.
Me.ArcClassTableAdapter.Fill(Me.ERVDataSet.ArcClass)
'TODO: This line of code loads data into the 'ERVDataSet.HousingFunctions' table. You can move, or remove it, as needed.
Me.HousingFunctionsTableAdapter.Fill(Me.ERVDataSet.HousingFunctions)
'TODO: This line of code loads data into the 'ERVDataSet.RoofMaterial' table. You can move, or remove it, as needed.
Me.RoofMaterialTableAdapter.Fill(Me.ERVDataSet.RoofMaterial)
'TODO: This line of code loads data into the 'ERVDataSet.WallMaterial' table. You can move, or remove it, as needed.
Me.WallMaterialTableAdapter.Fill(Me.ERVDataSet.WallMaterial)
'TODO: This line of code loads data into the 'ERVDataSet.FoundationMaterial' table. You can move, or remove it, as needed.
Me.FoundationMaterialTableAdapter.Fill(Me.ERVDataSet.FoundationMaterial)
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub Picturebox_Click(sender As System.Object, e As System.EventArgs) Handles FrontPhotoPicturebox.Click, RearLeftCornerPhotoPictureBox.Click, _
LeftFrontPhotoPictureBox.Click, RearRightCornerPhotoPictureBox.Click, StreetScape1PhotoPictureBox.Click, StreetScape2PhotoPictureBox.Click, RearLeftCornerPhotoPictureBox.Click, _
RightFrontCornerPhotoPictureBox.Click, RearPhotoPictureBox.Click, MapOfAPEPhotoPictureBox.Click, BuildingPlanPhotoPictureBox.Click
Dim pbxSender As PictureBox = DirectCast(sender, PictureBox)
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Images(.BMP.JPG.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
pbxSender.ImageLocation = OpenFileDialog1.FileName.ToString
End Sub
Private Sub Button1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown
Button1.BackColor = Color.GreenYellow
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
ReportEditor.Show()
End Sub
Public Sub SaveData()
Try
Me.Validate()
Me.ProjectsBindingSource.EndEdit()
Me.FoundationMaterialBindingSource.EndEdit()
Me.WallMaterialBindingSource.EndEdit()
Me.RoofMaterialBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.ERVDataSet)
Catch ex As Exception
MsgBox("Update failed")
End Try
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim ctrl As Control
Dim PicBx As PictureBox
For Each ctrl In GroupBox1.Controls
If (ctrl.GetType() Is GetType(PictureBox)) Then
PicBx = CType(ctrl, PictureBox)
PicBx.Image = Nothing
End If
Next
End Sub
End Class
So the first block of code is what I refer to as Form1 and the second is of course what I refer to as Form2 for disscussion purpouse. These are the two that need to interact. BTY this is only one of the 27 (and growing) controls I'll need to transfer values for. So is there a better way of doing this?
Life is about making some things happen, not waiting around for something to happen.
-
Feb 26th, 2013, 04:35 PM
#19
Re: Passing variables from form to form
I wasn't trying to specify any particular type of transfer in that thread. Passing information between two forms is the same as passing the information between any two objects. Forms are just a certain type of class, and are therefore like any other.
Every object can have a contstructor, as yours does, which is a pretty good way to get information into the object. Otherwise, an object only knows about what it is capable of acquiring. Therefore, it knows about its own internal stuff (such as controls, if it is a form), and it knows about stuff that you passed to it using either the constructor or Public Properties, and it knows about global stuff that everything knows about, which is what bentumkoitaba suggested. In your case, you are passing in stuff in the constructor, which is a good way to do it. However, you always have to have that stuff to pass it, because you can't make a new form without giving it that stuff. You can probably pass it Me.ERVDataset from wherever you want, as that looks like a member of the form that is creating the other form. Figuring out which ID you want to pass in for the integer is probably a bit harder. The ID appears to come from a datarow in one table. Do you know which row you want at the time of that event handler where you are having the problems?
My usual boring signature: Nothing
 
-
Feb 26th, 2013, 07:35 PM
#20
Thread Starter
Fanatic Member
Re: Passing variables from form to form
Well in post#18
Code:
Private Sub ProjectsDataGridView_DoubleClick(sender As Object, e As System.EventArgs) Handles ProjectsDataGridView.DoubleClick
Me.ProjectsBindingSource.EndEdit()
If Me.ProjectsBindingSource.Position > -1 Then
'Get the current product row
Dim row As ERVDataSet.ProjectsRow
row = CType(CType(Me.ProjectsBindingSource.Current, DataRowView).Row, ERVDataSet.ProjectsRow)
'Open the File form passing the dataset and the product ID
Dim projects As New File(Me.ERVDataSet, row.ProjectID)
projects.Show()
End If
The id is aquired and assigned to the Row var.
The Row var = the .current datarow of the ERVDataset.Project dataset.
So I guess I need to capture this id var. assign it to another var. in Form2 then pass it?
Last edited by crater; Feb 26th, 2013 at 07:45 PM.
Life is about making some things happen, not waiting around for something to happen.
-
Feb 27th, 2013, 03:07 PM
#21
Thread Starter
Fanatic Member
Re: Passing variables from form to form
Man I'm have a hard time trying to get the "id" of the constructor passed to this other form. can anyone guide me on this?
Life is about making some things happen, not waiting around for something to happen.
-
Feb 27th, 2013, 03:27 PM
#22
Re: Passing variables from form to form
Actually, the row variable is the datarow, so the id is not aquired and assigned to the Row var. The datarow is assigned to the row var, and that has the id as a field in the row. Therefore, the problem is quite likely not one of getting the id so much as getting the right datarow from which you obtain the id. Since the event in question is a TreeViewNode doubleclick, then it must be on a treeview. Does the node in the treeview correspond to a single record in the datatable? If not, then there is no viable id, so the design is bad. However, if the treeview node does correspond to a single record, the problem becomes on of figuring out how to determine that record based on the information in the e argument of the method. Beyond that, I can't say, since I have no idea what the treeview shows.
My usual boring signature: Nothing
 
-
Feb 27th, 2013, 04:18 PM
#23
Thread Starter
Fanatic Member
Re: Passing variables from form to form
ok maybe bad design then. The treeview just show the MS Word docs that want to edit. So maybe an oview of what I'm trying to do is in order.
(Form1) Search is a form with a datagridview loaded by a Access 2003 db through data adaptor. <--this is the startup form
(Form2) Projects is a form that displays the record in a detail view (with other controls) from the row the user click on in Search.
(Form3) ReportEditor is the form with the treeview. The nodes are the reports in a folder. The user clicks on a node and the corrisponding doc opens,
This is where i'm stuck. I need to pass the values from the controls in Projects to ReportEditor and finally to the report.
Beleive me when I say I'm lost. I was re-filling the dataset as a way to filter data orginally. I knew that was a bad way to filter so I searched and found the bindingsource.filter way from a chick named Beth Massi (I've learned alot from watching her vid "Forms over data series"). Now I'm left wondering if this was not so good, or moreso just way more advanced than me. BTY did they take the default instance out of VS2010? cause I cannot use something like Projects.anything. And I assume that is the default instance I've read about. It was great in vb6.
So back to the id problem.
Any ideas now that you can visualize what I'm trying to do?
Life is about making some things happen, not waiting around for something to happen.
-
Feb 27th, 2013, 04:58 PM
#24
Re: Passing variables from form to form
That helps quite a bit.
So, Form2 is showing a whole mess of records. Do you then choose one of those records, then go into Form3 and choose a report to run? If so, I wouldn't be doing ANY of that work in Form3. It should all be done in Form2. Assuming that my understanding is correct, Form3 is acting like a pick list. All it should do is allow the user to pick a report to run, and expose that as a public property on the form.
Form2 would then show Form3 modally (ShowDialog), and when that returns, it should look at the public property exposed by Form3 and do whatever work is needed.
Of course, if I misunderstood how the user would be working with these forms, that may not be correct.
My usual boring signature: Nothing
 
-
Feb 27th, 2013, 07:49 PM
#25
Thread Starter
Fanatic Member
Re: Passing variables from form to form
you about got it ; so to be a little more direct:
Form1: user picks record from datagridview --Click event get the datarow and hence the row id and opens Form2
Form2 opens with the data that was in the double_clicked row of Form1.datagridview and more, but in detail form.--Click event from here opens Form3
Form3 opens with a treeview from which the user can choose a report to run. I will need to load bookmarks in this form from controls on Form2 (mostly text propertys but there will be some images also.). This is so that they can be written to the report.
I see now that I don't need variables if Form2 is exposed to Form3 then the Form2.FirstNameTextBox.Text thing would work. I THINK
So maybe I should only be getting the node var. in Form3 and return it back to Form2 to do the work? There's alot of code in Form3 and even a call to module to get the folder icons just to populate the treeview and then retreive the correct node. Moving all of it is not something I would want to do if at all possible.
Oh yea, I'm not sure if Form3 should open modally as I will want to be able to open the reports for edit or just open protected. The difference is to unprotect or not which isn't a problem.
Last edited by crater; Feb 27th, 2013 at 08:18 PM.
Life is about making some things happen, not waiting around for something to happen.
-
Feb 28th, 2013, 10:10 AM
#26
Re: Passing variables from form to form
I can believe that Form3 does lots of work. Setting up Treeviews often requires lots of work. However, it also sounds like Form2 has all of the information necessary to provide to the report (possibly including the text properties and images), so it seems like Form3 should just be there so the user can choose the report, but all of the report building should really be done on Form2, where the necessary information resides.
Alternatively, if you feel that all the report work should be done in Form3, then I would add a constructor to Form3 (Sub New), which took the row ID, and possible the dataset, as arguments. Then, when Form2 launches Form3, it will have to supply the necessary information so that Form3 will have it.
My usual boring signature: Nothing
 
-
Feb 28th, 2013, 10:30 AM
#27
Thread Starter
Fanatic Member
Re: Passing variables from form to form
So to sum up the above, nothing needs to be returned back to form2. I just need to create a instance of Form2 in Form3 then the controls on Form2 will be exposed to Form3. But I create Form2 from Form1 with the constructor overloaded with Public Sub New (ByVal ds As ERVDataSet, ByVal id As Integer). So when I try to create a new instance of Form3 from Form2 it ask for the ds and id. dim form2 as new form2(Ervdataset,????) I can't seem to get the id portion of form2.
OK, posted the above after you shaggy replied.
I'll try the new constructor method but I guess I'm not sure why I need to overload the constructor with dataset and id when all I need is the value of the controls in Form2.
Bty I agree this method is throwing around alot a data between forms, but until I can figure out how to set up the proper properties in Form3 to return the correct info back to form2. So in realality I should set up a property in Form 3 thats value holds Form3 and then pass it to Form2?
Last edited by crater; Feb 28th, 2013 at 10:47 AM.
Life is about making some things happen, not waiting around for something to happen.
-
Feb 28th, 2013, 10:37 AM
#28
Re: Passing variables from form to form
No, that's not so good. You'd be wasting a perfectly good form. You already HAVE a Form2, don't go creating another one. Your two options are these:
1) Use Form3 ONLY to choose which report, but do all the report building on Form2. Therefore, Form2 shows Form3 for the sole purpose of getting the report to build, which Form3 passes back to Form2 via a public property on Form3.
2) Use Form3 to build the report, but in this case, it must receive all the information it needs from Form2 (like the ID, and possibly the dataset), in which case they should be passed as arguments in the constructor for Form3.
There is never a good reason for Form3 to create a Form2. The goal is to identify the role that each form will serve, and keep that as minimal as possible. Both of the options presented have exactly one instance of Form2 and create one instance of Form3.
My usual boring signature: Nothing
 
-
Feb 28th, 2013, 11:31 AM
#29
Thread Starter
Fanatic Member
Re: Passing variables from form to form
So if I move this block of code minus the constructor to Form2's button click event that showed Form3:
Code:
Public Sub TreeView1_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
' only proceed if the node represents a file
If e.Node.ImageKey = "folder" Then Exit Sub
If e.Node.Tag Is "" Then Exit Sub
' try to open the file
Try
If e.Node.ImageKey = ".doc" Or e.Node.ImageKey = ".docx" Then
Dim oWord As Word.Application
Dim oDoc As Word.Document
' ''Start Word and open the document template.
oWord = CType(CreateObject("Word.Application"), Word.Application)
oDoc = oWord.Documents.Open(e.Node.Tag)
''Set the position of the Word App.
oDoc.Windows(1).WindowState = Word.WdWindowState.wdWindowStateNormal
oDoc.Windows(1).Application.Top = 52
oWord.Visible = True
Dim project As New Projects(projects)
If oDoc.ProtectionType = Word.WdProtectionType.wdAllowOnlyFormFields Then
oDoc.Unprotect()
End If
oDoc.Variables("T1").Value = project.FirstNameTextBox.Text
'oDoc.Bookmarks("t1").Range.Text = myfile.FirstNameTextBox.Text
oDoc.Fields.Update()
oDoc.Fields.Unlink()
oWord = Nothing
oDoc = Nothing
End If
If e.Node.ImageKey = ".xls" Or e.Node.Tag Is ".xlsx" Then
'Keep the application object and the workbook object global, so you can
'retrieve the data in Button2_Click that was set in Button1_Click.
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet
' Create a new instance of Excel and start a new workbook.
objApp = New Excel.Application()
objBooks = objApp.Workbooks
objBook = objBooks.Open(CStr(e.Node.Tag))
objSheets = objBook.Worksheets
objSheet = CType(objSheets(1), Excel._Worksheet)
'Make it Visible to the user now that we are going to use it
objApp.Visible = True
''Set the position of the Excel App.
objApp.Windows(1).Application.WindowState = Excel.XlWindowState.xlNormal
objApp.Windows(1).WindowState = Excel.XlWindowState.xlMaximized
objApp.Windows(1).Application.Top = 55
'Make sure our object variable is destroyed and released since its going out of scope
objApp = Nothing
End If
Catch ex As Exception
MessageBox.Show("Error opening file: " & ex.Message)
End Try
End Sub
And set this property in Form3
Code:
Private Form3 As ReportEditor
Public Property Frm3 As ReportEditor
Get
Return Form3
End Get
Set(value As ReportEditor)
Form3 = value
End Set
End Property
Then how do I access Form3 from Form2
Dim FormEditor as Form3 ??????????
Now I don't think I have my properties set correctly. I think the property should be the picked node. Correct??
Last edited by crater; Feb 28th, 2013 at 11:35 AM.
Life is about making some things happen, not waiting around for something to happen.
-
Feb 28th, 2013, 03:26 PM
#30
Re: Passing variables from form to form
Yes....maybe. The node may have all the information you need, or it may be much more than you need. I'd make the property as simple as possible. If you need only one item from the node, then make the property just that item. If you need more than one item, then the node might be the best way to go. Alternatively, you could have multiple properties, one for each necessary item.
After looking at the earlier code, it looks like the node would be reasonable, as it contains a variety of things that you appear to want.
EDIT: I guess I never answered the actual question. If you have this line:
dim FormEditor As New Form3 (you need that New in there).
then you show it with:
FormEditor.ShowDialog
dim node = FormEditor.Frm3Node (assuming you change the property to return a node, and change the property name to Frm3Node, but that's a rather silly name, so you can come up with something better).
My usual boring signature: Nothing
 
-
Feb 28th, 2013, 08:09 PM
#31
Thread Starter
Fanatic Member
Re: Passing variables from form to form
ok I moved this code into Form1
Code:
Public Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'If ReportEditor Is Nothing OrElse ReportEditor.IsDisposed = True Then
Dim ReportEditor As New ReportEditor
'End If
'If ReportEditor.Visible = False Then
ReportEditor.ShowDialog()
Dim node = ReportEditor.node
' only proceed if the node represents a file
If node.ImageKey = "folder" Then Exit Sub '<-----THIS IS WHERE THE ERROR OCCURS
If node.Tag Is "" Then Exit Sub
' try to open the file
Try
If node.ImageKey = ".doc" Or node.ImageKey = ".docx" Then
Dim oWord As Word.Application
Dim oDoc As Word.Document
' ''Start Word and open the document template.
oWord = CType(CreateObject("Word.Application"), Word.Application)
oDoc = oWord.Documents.Open(node.Tag)
''Set the position of the Word App.
oDoc.Windows(1).WindowState = Word.WdWindowState.wdWindowStateNormal
oDoc.Windows(1).Application.Top = 52
oWord.Visible = True
If oDoc.ProtectionType = Word.WdProtectionType.wdAllowOnlyFormFields Then
oDoc.Unprotect()
End If
oDoc.Variables("T1").Value = Me.FirstNameTextBox.Text ''This is what I need to Set
'oDoc.Bookmarks("t1").Range.Text = myfile.FirstNameTextBox.Text
oDoc.Fields.Update()
oDoc.Fields.Unlink()
oWord = Nothing
oDoc = Nothing
End If
'If node.ImageKey = ".xls" Or node.Tag Is ".xlsx" Then
' 'Keep the application object and the workbook object global, so you can
' 'retrieve the data in Button2_Click that was set in Button1_Click.
' Dim objApp As Excel.Application
' Dim objBook As Excel._Workbook
' Dim objBooks As Excel.Workbooks
' Dim objSheets As Excel.Sheets
' Dim objSheet As Excel._Worksheet
' ' Create a new instance of Excel and start a new workbook.
' objApp = New Excel.Application()
' objBooks = objApp.Workbooks
' objBook = objBooks.Open(CStr(node.Tag))
' objSheets = objBook.Worksheets
' objSheet = CType(objSheets(1), Excel._Worksheet)
' 'Make it Visible to the user now that we are going to use it
' objApp.Visible = True
' ''Set the position of the Excel App.
' objApp.Windows(1).Application.WindowState = Excel.XlWindowState.xlNormal
' objApp.Windows(1).WindowState = Excel.XlWindowState.xlMaximized
' objApp.Windows(1).Application.Top = 55
' 'Make sure our object variable is destroyed and released since its going out of scope
' objApp = Nothing
'End If
Catch ex As Exception
MessageBox.Show("Error opening file: " & ex.Message)
End Try
End Sub
Public Sub SaveData()
Try
Me.Validate()
Me.ProjectsBindingSource.EndEdit()
Me.FoundationMaterialBindingSource.EndEdit()
Me.WallMaterialBindingSource.EndEdit()
Me.RoofMaterialBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.ERVDataSet)
Catch ex As Exception
MsgBox("Update failed")
End Try
End Sub
re-wrote the Property in Form3:
Code:
Public node As TreeNode
Public Property ReportNode As TreeNode
Get
Return node
End Get
Set(value As TreeNode)
node = value
End Set
End Property
And added this to the treeview double click event:
Code:
Public Sub TreeView1_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
node = Me.TreeView1.SelectedNode
end sub
Now when I run it. Form3 does not show(or at least stay showed) for me to invoke the double click event.
it returns back to Form2 and errors saying. "Object reference not set to an instance of an object" this breaks on line where I check if node.imagekey = "folder"
Well duh it's gonna be null cause the node has not been set. But why is Form3 not showing and waiting for the user?
Life is about making some things happen, not waiting around for something to happen.
-
Mar 1st, 2013, 10:19 AM
#32
Re: Passing variables from form to form
That's the right question. To figure it out, how about putting a breakpoint on the ShowDialog line and stepping into it? The problem is that you are doing something that is closing Form3, but what that is I can't say. Stepping through it will show you, though.
My usual boring signature: Nothing
 
-
Mar 1st, 2013, 10:42 AM
#33
Thread Starter
Fanatic Member
Re: Passing variables from form to form
Ok, I set breakpoint on showdialog.
App. breaks on showdialog
Step into (F8) app. goes to ReportEditor form load event. stepping through code it runs down through the sub and functions into the module to end function and back the showdialog then to end sub. Which leave Form2 open but there are no calls to close ReportEditor, no if then exit subs nothing like that.
Code in ReportEditor:
Code:
Option Explicit On
Option Strict On
'Add a reference to MS Excel xx.0 Object Library
'Import the Excel Primary Interop Assembly
Imports Microsoft.Office.Interop
Public Class ReportEditor
Inherits System.Windows.Forms.Form
Private mRootPath As String = My.Settings.ReportsPath '"C:\Users\Matt\Desktop\ERV\Reports"
Property RootPath As String
Get
Return mRootPath
End Get
Set(value As String)
mRootPath = value
End Set
End Property
Private node As TreeNode
Public Property ReportNode As TreeNode
Get
Return node
End Get
Set(value As TreeNode)
node = value
End Set
End Property
Private Sub ReportEditor_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
InitializeComponent()
Me.MdiParent = Home
' when our component is loaded, we initialize the TreeView by adding the root node
Dim mRootNode As New TreeNode
mRootNode.Text = RootPath
mRootNode.Tag = RootPath
mRootNode.Nodes.Add("*DUMMY*")
TreeView1.Nodes.Add(mRootNode)
mRootNode.ImageKey = CacheShellIcon(RootPath)
mRootNode.SelectedImageKey = mRootNode.ImageKey
End Sub
Private Sub TreeView1_BeforeCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeCollapse
' clear the node that is being collapsed
e.Node.Nodes.Clear()
' add a dummy TreeNode to the node being collapsed so it is expandable
e.Node.Nodes.Add("*DUMMY*")
End Sub
Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
' clear the expanding node so we can re-populate it, or else we end up with duplicate nodes
e.Node.Nodes.Clear()
' get the directory representing this node
Dim mNodeDirectory As IO.DirectoryInfo
mNodeDirectory = New IO.DirectoryInfo(e.Node.Tag.ToString)
' add each subdirectory from the file system to the expanding node as a child node
For Each mDirectory As IO.DirectoryInfo In mNodeDirectory.GetDirectories
' declare a child TreeNode for the next subdirectory
Dim mDirectoryNode As New TreeNode
' store the full path to this directory in the child TreeNode's Tag property
mDirectoryNode.Tag = mDirectory.FullName
' set the child TreeNodes's display text
mDirectoryNode.Text = mDirectory.Name
mDirectoryNode.ImageKey = CacheShellIcon(mDirectory.FullName)
mDirectoryNode.SelectedImageKey = mDirectoryNode.ImageKey
' add a dummy TreeNode to this child TreeNode to make it expandable
mDirectoryNode.Nodes.Add("*DUMMY*")
' add this child TreeNode to the expanding TreeNode
e.Node.Nodes.Add(mDirectoryNode)
Next
' add each file from the file system that is a child of the argNode that was passed in
For Each mFile As IO.FileInfo In mNodeDirectory.GetFiles
' declare a TreeNode for this file
Dim mFileNode As New TreeNode
' store the full path to this file in the file TreeNode's Tag property
mFileNode.Tag = mFile.FullName
' set the file TreeNodes's display text
mFileNode.Text = mFile.Name
mFileNode.ImageKey = CacheShellIcon(mFile.FullName)
mFileNode.SelectedImageKey = mFileNode.ImageKey & "-open"
' add this file TreeNode to the TreeNode that is being populated
e.Node.Nodes.Add(mFileNode)
Next
End Sub
Private objApp As Excel.Application
Private oWord As Word.Application
Public Sub TreeView1_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
node = Me.TreeView1.SelectedNode
'' only proceed if the node represents a file
'If e.Node.ImageKey = "folder" Then Exit Sub
'If e.Node.Tag Is "" Then Exit Sub
'' try to open the file
'Try
' If e.Node.ImageKey = ".doc" Or e.Node.ImageKey = ".docx" Then
' Dim oWord As Word.Application
' Dim oDoc As Word.Document
' ' ''Start Word and open the document template.
' oWord = CType(CreateObject("Word.Application"), Word.Application)
' oDoc = oWord.Documents.Open(e.Node.Tag)
' ''Set the position of the Word App.
' oDoc.Windows(1).WindowState = Word.WdWindowState.wdWindowStateNormal
' oDoc.Windows(1).Application.Top = 52
' oWord.Visible = True
' If oDoc.ProtectionType = Word.WdProtectionType.wdAllowOnlyFormFields Then
' oDoc.Unprotect()
' End If
' oDoc.Variables("T1").Value = ''This is what I need to Set
' 'oDoc.Bookmarks("t1").Range.Text = myfile.FirstNameTextBox.Text
' oDoc.Fields.Update()
' oDoc.Fields.Unlink()
' oWord = Nothing
' oDoc = Nothing
' End If
' If e.Node.ImageKey = ".xls" Or e.Node.Tag Is ".xlsx" Then
' 'Keep the application object and the workbook object global, so you can
' 'retrieve the data in Button2_Click that was set in Button1_Click.
' Dim objApp As Excel.Application
' Dim objBook As Excel._Workbook
' Dim objBooks As Excel.Workbooks
' Dim objSheets As Excel.Sheets
' Dim objSheet As Excel._Worksheet
' ' Create a new instance of Excel and start a new workbook.
' objApp = New Excel.Application()
' objBooks = objApp.Workbooks
' objBook = objBooks.Open(CStr(e.Node.Tag))
' objSheets = objBook.Worksheets
' objSheet = CType(objSheets(1), Excel._Worksheet)
' 'Make it Visible to the user now that we are going to use it
' objApp.Visible = True
' ''Set the position of the Excel App.
' objApp.Windows(1).Application.WindowState = Excel.XlWindowState.xlNormal
' objApp.Windows(1).WindowState = Excel.XlWindowState.xlMaximized
' objApp.Windows(1).Application.Top = 55
' 'Make sure our object variable is destroyed and released since its going out of scope
' objApp = Nothing
' End If
'Catch ex As Exception
' MessageBox.Show("Error opening file: " & ex.Message)
'End Try
End Sub
Function CacheShellIcon(ByVal argPath As String) As String
Dim mKey As String = Nothing
' determine the icon key for the file/folder specified in argPath
If IO.Directory.Exists(argPath) = True Then
mKey = "folder"
ElseIf IO.File.Exists(argPath) = True Then
mKey = IO.Path.GetExtension(argPath)
End If
' check if an icon for this key has already been added to the collection
If ImageList1.Images.ContainsKey(mKey) = False Then
ImageList1.Images.Add(mKey, GetShellIconAsImage(argPath))
ImageList1.Images.Add(mKey & "-open", GetShellOpenIconAsImage(argPath))
End If
Return mKey
End Function
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' 'Create our generic unknown object variable and trap for Excel not installed
' Try
' objApp = DirectCast(CreateObject("Excel.Application"), Excel.Application)
' 'Keep it hidden from the user until we need to use it
' objApp.Visible = False
' Catch ex As Exception
' MessageBox.Show(ex.Message, "VB/Office Guru™ Excel Early Binding VB.NET Automation FAQ", _
' MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
' End Try
'End Sub
'Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
'Handles MyBase.Closing
' 'Check if Excel Application is still instanciated
' If IsNothing(objApp) = False Then
' 'Check if our Excel instance has any opened workbooks in it
' If objApp.Workbooks.Count > 0 Then
' 'Close all open workbooks not saving them
' 'Loop backwards so the index information will be relevant as they close
' For i As Integer = objApp.Workbooks.Count To 1 Step -1
' objApp.Workbooks.Item(i).Close(SaveChanges:=False)
' Next
' End If
' 'Close our Excel Application object
' objApp.Quit()
' End If
' 'Make sure its destroyed
' objApp = Nothing
' 'Absolutely none of our Excel instances will be left running!
'End Sub
End Class
Code in the Module:
Code:
Module Module1
Public Declare Auto Function SHGetFileInfo Lib "shell32.dll" (ByVal pszPath As String, ByVal dwFileAttributes As Integer, ByRef psfi As SHFILEINFO, ByVal cbFileInfo As Integer, ByVal uFlags As Integer) As IntPtr
Public Const SHGFI_ICON As Integer = &H100
Public Const SHGFI_SMALLICON As Integer = &H1
Public Const SHGFI_LARGEICON As Integer = &H0
Public Const SHGFI_OPENICON As Integer = &H2
Structure SHFILEINFO
Public hIcon As IntPtr
Public iIcon As Integer
Public dwAttributes As Integer
<Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=260)> _
Public szDisplayName As String
<Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=80)> _
Public szTypeName As String
End Structure
' GetShellIconAsImage
Function GetShellIconAsImage(ByVal argPath As String) As Image
Dim mShellFileInfo As New SHFILEINFO
mShellFileInfo.szDisplayName = New String(Chr(0), 260)
mShellFileInfo.szTypeName = New String(Chr(0), 80)
SHGetFileInfo(argPath, 0, mShellFileInfo, System.Runtime.InteropServices.Marshal.SizeOf(mShellFileInfo), SHGFI_ICON Or SHGFI_SMALLICON)
' attempt to create a System.Drawing.Icon from the icon handle that was returned in the SHFILEINFO structure
Dim mIcon As System.Drawing.Icon
Dim mImage As System.Drawing.Image
Try
mIcon = System.Drawing.Icon.FromHandle(mShellFileInfo.hIcon)
mImage = mIcon.ToBitmap
Catch ex As Exception
' for some reason the icon could not be converted so create a blank System.Drawing.Image to return instead
mImage = New System.Drawing.Bitmap(16, 16)
End Try
' return the final System.Drawing.Image
Return mImage
End Function
Function GetShellOpenIconAsImage(ByVal argPath As String) As Image
Dim mShellFileInfo As New SHFILEINFO
mShellFileInfo.szDisplayName = New String(Chr(0), 260)
mShellFileInfo.szTypeName = New String(Chr(0), 80)
SHGetFileInfo(argPath, 0, mShellFileInfo, System.Runtime.InteropServices.Marshal.SizeOf(mShellFileInfo), SHGFI_ICON Or SHGFI_SMALLICON Or SHGFI_OPENICON)
' attempt to create a System.Drawing.Icon from the icon handle that was returned in the SHFILEINFO structure
Dim mIcon As System.Drawing.Icon
Dim mImage As System.Drawing.Image
Try
mIcon = System.Drawing.Icon.FromHandle(mShellFileInfo.hIcon)
mImage = mIcon.ToBitmap
Catch ex As Exception
' for some reason the icon could not be converted so create a blank System.Drawing.Image to return instead
mImage = New System.Drawing.Bitmap(16, 16)
End Try
' return the final System.Drawing.Image
Return mImage
End Function
End Module
So can you see what I'm missing?
Life is about making some things happen, not waiting around for something to happen.
-
Mar 1st, 2013, 11:11 AM
#34
Re: Passing variables from form to form
If I understand you right, you are saying that when you stepped through the code you got to this line:
mRootNode.ImageKey = CacheShellIcon(RootPath)
and then stepped into the CacheShellIcon method in the module, stepped through that to the end, and then what? It sounds like it went right back to the ShowDialog at that point.
Did it not get to this line?
mRootNode.SelectedImageKey = mRootNode.ImageKey
The next thing I would do would be to wrap the Load event code in a Try....Catch block with a messagebox to display any error. There is some really odd behavior that can happen if an exception is thrown in form load events (not on all systems, but so what). If an exception is thrown, it may cause no error message at all, just really odd, quiet, behavior. If that line wasn't reached, that could be the issue, though I'd be surprised if it manifested in this way.
One other thing that can do it would be if the dialogResult was being set for the form.
My usual boring signature: Nothing
 
-
Mar 1st, 2013, 11:31 AM
#35
Thread Starter
Fanatic Member
Re: Passing variables from form to form
No, I can step through past that line, entering the CacheShell method, returning back to the next line, mRootNode.SelectedImageKey = mRootNode.ImageKey
then stepping through it goes to the next line End Sub, which return back to Form2 to line showdialog.
Life is about making some things happen, not waiting around for something to happen.
-
Mar 1st, 2013, 11:36 AM
#36
Thread Starter
Fanatic Member
Re: Passing variables from form to form
I place the Try Catch as suggested. Stepped through again and no exception was caught. Maybe my Try Catch is setup wrong?
Code:
Private Sub ReportEditor_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Me.MdiParent = Home
' when our component is loaded, we initialize the TreeView by adding the root node
Dim mRootNode As New TreeNode
mRootNode.Text = RootPath
mRootNode.Tag = RootPath
mRootNode.Nodes.Add("*DUMMY*")
TreeView1.Nodes.Add(mRootNode)
mRootNode.ImageKey = CacheShellIcon(RootPath)
mRootNode.SelectedImageKey = mRootNode.ImageKey
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Life is about making some things happen, not waiting around for something to happen.
-
Mar 1st, 2013, 12:30 PM
#37
Re: Passing variables from form to form
Try moving this code to the shown event and see if you have different results..
-
Mar 1st, 2013, 02:55 PM
#38
Re: Passing variables from form to form
Your Try...Catch is set up correctly. Since you got no message, you didn't get an exception, and that was not the problem.
At this point, I'd have to say that I have no sound suggestion. From what you described, you don't appear to have done anything in particular in the Load event that would either close the form (Me.Close), or set the DialogResult to something. There is one further test you could look at: You could get the return value from ShowDialog, and see what it is. Unfortunately, I'm not sure that there is a good default value for this. Therefore, if it is Cancel, that is probably meaningless. If it is OK, that would be interesting.
Failing that, I would say that you should mark this thread as resolved, and start a new one as to why the form is closing unexpectedly. The point would be that you would get fresh eyes on the subject. There is probably some other means of closing a form that I'm not aware of, but this thread is now so lengthy that lots of people won't read through it to get to this part, and this part is clearly a different question from the subject line and the opening question.
My usual boring signature: Nothing
 
-
Mar 1st, 2013, 03:53 PM
#39
Thread Starter
Fanatic Member
Re: Passing variables from form to form
I agree, thanks for the help. I have a way better understanding of passing values across Class's through public propertys now due to this thread and your help. I will begin a new thread regarding the form closing.
Life is about making some things happen, not waiting around for something to happen.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|