how to pass value from one form to another?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: how to pass value from one form to another?

  1. #1
    Join Date
    Feb 2013
    Posts
    29

    how to pass value from one form to another?

    Hi everybody,

    i am trying to create a form app with multiple forms. there is a form i'm using as "search". i want to take the value of the textbox in search-form and pass it to another form which shows the result of the search. i've tried to include search-form.h in the form of the result but it returns an error.

    Code:
    	
    String ^ key;
    key = searchbox->Text;
    std::string ks = marshal_as<std::string>(key);
    ks=ks+".bin";
    
    
    	ifstream sfile(ks);
    			
            	if (sfile)
    		{
                       PatInfo ^ form = gcnew PatInfo;
    		   form->ShowDialog();
    					
    		}												
    		else 
    			{
     			 MessageBox::Show( "Please try again.");
    			}
    to conclude, i want the form PatInfo to open an receive the "ks" var. thanks in advance!!

  2. #2
    Join Date
    Feb 2013
    Posts
    29

    Re: how to pass value from one form to another?

    i believe that it can be solved by a header file in which i declare the variables, so i wrote this
    Code:
    #ifndef GLOB_H_INCLUDED
    #define GLOB_H_INCLUDED
    #include <string.h>
    #include <windows.h>
    
    
    using namespace std;
    
    extern string ks;
    extern int leftc, rightc, middlec;
    
    
    #endif
    i use this to keep the value of the ks var so as to use it in another form but it doesn't work. i added ks in watch window and i realize that as soon as the compiler finds the declaration of ks in the new form the old value is lost but if i don't declare it i can't use it... any ideas?
    Last edited by The_Sire; March 12th, 2013 at 05:44 PM.

  3. #3
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,591

    Re: how to pass value from one form to another?

    Quote Originally Posted by The_Sire View Post
    i believe that it can be solved by a header file in which i declare the variables, so i wrote this

    [...]
    No, that doesn't solve anything. In fact it severely worsens things! There's almost never a good reason to involve any native C++ stuff in a new .NET app you're writing (i.e. unless you're extending an already existing native app with .NET code, and even that is questionable). Mixing native and managed code without a reason severely and, more important, unnecessarily complicates things. And using the native C++ standard library in a C++/CLI app is about the most terrible variant of that mistake I've ever seen, since almost anything offered by the C++ standard library can be achieved with the .NET framework infrastructure as well. The almost only case in which I'd probably always accept native code to be integrated into a .NET app is integrating a great native lirary to which no .NET alternative is available.

    In the code snippet from your initial post, for instance, there's no need to use any native library stuff at all. Using the .NET framework library method File::Exists() (and perhaps Path::Combine()), the first five lines (not counting blank lines) can be contracted into a single one.

    Although I can't really tell for sure from your rudimentary code snippet, I don't think the above is the reason why you got the original error message that made you start this thread, though. The symptoms are typical for a circular inclusion which is a quite common prolem discussed here quite some times. The solution is to separate the form's (both forms) implementation from the class body in the .h file into a separate .cpp implementation file. You can see what that looks like in practically any sample code I posted or uploaded in this section. The discussion about why that's the case and tips on the individual steps to take can be found in fewer threads, but it's still quite some. The forum search feature still doesn't seem to have completely recovered from the (not so recent anymore) forum software update : There most certainly have been more than two threads about that topic since 2010. Here are two I found without using forum search: http://forums.codeguru.com/showthrea...Cyclic-Include, http://forums.codeguru.com/showthrea...em-in-a-dialog
    Last edited by Eri523; March 16th, 2013 at 09:54 AM. Reason: Added link to another cyclic inclusion thread
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  4. #4
    Join Date
    Feb 2013
    Posts
    29

    Re: how to pass value from one form to another?

    the big question is how can I pass variables of one forms to another. should i use pointers or is there a function that does this??? i've allready corrected errors and stop using the .h file. thanks for the help with Path::Combine()!!!!!

  5. #5
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,591

    Re: how to pass value from one form to another?

    Well, I didn't consider that the primary problem when reading your initial post, especially since IMO that's much simpler than sorting out the circular inclusion issue.

    You simply need to make the variable in question visible to the invoking form. Usually you'd make it pulic for that purpose. If, in this case, it's a String ^ variale (note the capital S) that you declared yourself, you'd simply do that by placing the declaration after a public:, and then, in your main form, you'd assign it the desired text like this: form->VariableForFileName = FileNameFound;. If you want to directly assign the file name to a control (e.g. a text box or label) to display it, you'd make that control publicly visible which you can do in the control's properties in Form's Designer (don't remember the exact name of the property now, but it should be rather obvious). You'd then assign the desired text like this: form->ControlForFileName->Text = FileNameFound;
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  6. #6
    Join Date
    Jan 2010
    Posts
    1,100

    Re: how to pass value from one form to another?

    Rather then making internal variables public, it's better to provide getters and setters. Furthermore, if it's only the text property you need to get, you don't need to expose the control at all - you just need to provide a public member functions which returns the string in question. This allows you to control what aspects of the state are exposed and under what rules, and thus to maintain encapsulation (you don't want you form's internal state directly manipulated by some other class - as this might, by accident or by malicious intention, cause some bugs, and break class invariants).

    This question relatively often pops up at C# forum. Besides defining a proper public interface, the other consideration here is how to go about making one form instance visible to another. There are several approaches. You can make one form internally maintain a reference (.NET handle) to another. The reference would be obtained either externally (whatever code creates the second form also passes its .NET handle to either a constructor, a property, or a member function of the first form), or internally (if the first form is responsible for creating the second, than it can simply assign it to an internal variable).
    Code:
    +-----------+        +-----------+
    |   Form1   |        |   Form2   |
    |  m_frm2 --+------->|           |
    +-----------+        +-----------+
    Finally, you can have a globally available helper class, or a "hub" of sorts, which could maintain private static references to both forms, and provide public static accessor functions, available from any part of the program, so that one form can access the other through them.

    Code:
            +-------------+
            |   Windows   |
            |  GetForm1() |
            |  GetForm2() |
            +-------------+
                   ^
                   .
                   .
         . . . .(global). . . . 
         .                    .
         .                    .
    +-----------+        +-----------+
    |   Form1   |        |   Form2   |
    |           |        |           |
    +-----------+        +-----------+
    Once there is a means available to access the second form, the rest is just a matter of using the existing public interface.

    P.S. You could also rely on events, but that's probably uncalled for; besides, setting aside the fact that event listeners usually register for the event by themselves, under the hood, the event approach is not all that different from the internal reference based approach described above (when an object subscribes to an event, the event provider stores a reference to that object, so that it can notify it when the time comes).
    Last edited by TheGreatCthulhu; March 12th, 2013 at 09:00 PM.

  7. #7
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,591

    Re: how to pass value from one form to another?

    TheGreatCthulhu, from a design POV, of course, you're perfectly right. However, I tend to allow beginners some degree of hackishness in their code to get simple, working solutions until the really bad things have been sorted out (like unnecessary native code in a .NET app, sic!). The nifty and sometimes rather advanced design details can then be introduced some posts later, or even some threads later, if the OP stays long enough.

    Admittedly , it's not so rare that I allow class-external access to data members myself, but mostly only assemly-internal, so it's not exposed over the public assembly interface visible to library client code, and/or in a rather experimental stage of development.

    Quote Originally Posted by TheGreatCthulhu View Post
    This question relatively often pops up at C# forum.
    Can you link me to one or a few representative threads of that kind? That may give me a better view of the "canonical" .NET perspective on that suject.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  8. #8
    Join Date
    Jan 2010
    Posts
    1,100

    Re: how to pass value from one form to another?

    Well, I did say "relatively often", but apparently not so often that I can find the damned things at the moment (tried forum search and google...). But, then I remembered that one time someone gave the OP a link to a CodeProject article, and, as it turns out, the question relatively often pops up at CodeProject as well, and there are several articles on the topic to be found there, so I suppose they can serve the purpose, so I'll give you links to those instead:
    http://www.codeproject.com/Articles/...1-x-with-C-and
    http://www.codeproject.com/Articles/...-Between-Forms
    http://www.codeproject.com/Articles/...-Windows-Forms (using delegates and events)
    http://www.codeproject.com/Questions...m-Another-Form

    But, it all comes down to what you need to do, and how do you need to connect the two forms - and this is no different than establishing communication between two objects of any type. In a more advanced scenarios, once could exploit preexisting events, or databinding capabilities, or base the interaction on the MVP architectural style.

    P.S. And here's one really short and simple from MSDN: http://msdn.microsoft.com/en-us/libr...=vs.71%29.aspx
    Last edited by TheGreatCthulhu; March 12th, 2013 at 10:13 PM.

  9. #9
    Join Date
    Jun 2011
    Posts
    25

    Re: how to pass value from one form to another?

    Quote Originally Posted by Eri523 View Post
    TheGreatCthulhu, from a design POV, of course, you're perfectly right. However, I tend to allow beginners some degree of hackishness in their code to get simple, working solutions until the really bad things have been sorted out (like unnecessary native code in a .NET app, sic!). The nifty and sometimes rather advanced design details can then be introduced some posts later, or even some threads later, if the OP stays long enough.
    I can second that wholeheartedly! From my experience I know for sure that without your help in particular I would have given up on codeguru long ago. For non-pro VC++ users like myself a simple clear example is the best help you can give or get.
    Last edited by RogerD; March 16th, 2013 at 07:38 AM. Reason: Mistake in attachment

  10. #10
    Join Date
    Jan 2010
    Posts
    1,100

    Re: how to pass value from one form to another?

    I have to insist, because, in the long run, if a beginner develops a habit of exposing private members, it's a rather bad thing (experienced developers can break or bend the rules, but only because they understand them well enough to do so). Good design is important, and, besides, what I'm proposed up there isn't that complicated at all.

    I attached an example project below. The approach I demonstrated is based on the "central hub" design.
    Basically, there are two form classes, Form1 and Form2. Form 1 contains an input TextBox, while Form2 contains a read-only label that will reproduce in real time whatever you're typing on Form1.

    In order for Form2 to be able to accept text data from some other peace of code, it must define a way for that code to pass the data along (that is, it must have an appropriate public interface for the task). This simply means that it needs to have a public member function which accepts a string, and then sets it as the value of the Text property of the label:

    Code:
    public:
    	void SetUserText(String^ text)
     	{
    		_labelUserText->Text = text;
    	}

    The project also contains a class I named Program, which represents the "hub". It has a private constructor, and it contains two public static functions:
    Code:
    // in Program.h
    
    public ref class Program
    {
    private:
    	Program() {}
    
    public:
    	static Form1^ GetForm1();
    	static Form2^ GetForm2();
    
    private:
    	static Form1^ s_form1 = nullptr;
    	static Form2^ s_form2 = nullptr;	// NOTE: it can even be a form of the same type, in certain scenarios
    };
    Code:
    // in Program.cpp
    
    Form1^ Program::GetForm1()
    {
    	if (!s_form1 || s_form1->IsDisposed)
    		s_form1 = gcnew Form1();
    
    	return s_form1;
    }
    
    
    Form2^ Program::GetForm2()
    {
    	if (!s_form2 || s_form2->IsDisposed)
    		s_form2 = gcnew Form2();
    
    	return s_form2;
    }
    As you can see, they simply return the static form instance (and check if it needs to be recreated).

    Finally, in Form1, there's a handler for the text box' TextChanged event, which is responsible for passing data to Form2:
    Code:
    System::Void Form1::_textBox_TextChanged(System::Object^  sender, System::EventArgs^  e)
    {
    	Program::GetForm2()->SetUserText(_textBox->Text);
    }
    As you can see, it simply uses the static function from Program to get the Form2 instance, and then calls it's SetUserText() member function. Not overly complicated at all.

    (Note: It's a VS2010 project.)
    Attached Files Attached Files
    Last edited by TheGreatCthulhu; March 13th, 2013 at 08:47 AM.

  11. #11
    Join Date
    Feb 2013
    Posts
    29

    Re: how to pass value from one form to another?

    thanks everyone for the help i think i've done it! any ideas on how can i split a string? if str1= "Name : Sire", str2="Sire" (i dont care about the "Name : " since i dont need it...)

  12. #12
    Join Date
    Jan 2010
    Posts
    1,100

    Re: how to pass value from one form to another?

    You can use the String::Split() method (function) - it returns an array<String^>^, so you can just do str1->Split(':'), and then take the last member, trim any whitespace using String::Trim(), and assign the result to str2.

  13. #13
    Join Date
    Feb 2013
    Posts
    29

    Re: how to pass value from one form to another?

    i used String::Split ()... thanks again... would you say that if i ask something once again in the same post I'll be completly out of topic Anyway, I want to insert in this cobe something to count every mouse click (not only in the front form) and display them when start button is pressed
    Code:
    public: System::Void StartB_Click(System::Object^  sender, System::Windows::Forms::MouseEventArgs e)
    			 {
    
    				if (e.Button == ::MouseButtons::Left)
    				{
    					l++;
    				}
    				else if (e.Button == ::MouseButtons::Right)
    				{
    					r++;
    				}
    				else if (e.Button == ::MouseButtons::Middle)
    				{
    					m++;
    				} 
    			 }
    I tryied this but it doesn't seem to work...

    thanks for the help so far! you were fantastic!!!
    Last edited by The_Sire; March 13th, 2013 at 04:35 PM.

  14. #14
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,591

    Re: how to pass value from one form to another?

    Quote Originally Posted by The_Sire View Post
    would you say that if i ask something once again in the same post I'll be completly out of topic
    I'd say that depends. The string splitting question was rather easy to answer comprehensively, but what you're asking here is quite tricky and definitely deserves a new thread.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  15. #15
    Join Date
    Feb 2013
    Posts
    29

    Re: how to pass value from one form to another?

    how do i declare this thread solved??

Page 1 of 2 12 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center