简体   繁体   中英

How to transfer value from one Form to another?

Ok Here is what I want. I have created a Class

public class docname
    {
        private string doctname;

        public string Doctname
        {
            get { return doctname; }
            set { doctname = value; }
        }
    }

and I have used it in a form

public string name;
docname dc = new docname();
dc.Doctname = name;

and when I check the value in another form I get a null value. Whats the reason behind this?

I am a beginner at C#.

Well, in your code sample, you're not actually assigning anything to the public string name variable, so it will be null until you assign a value to it. Assuming that's just a typo, you need to make sure that both of your forms are referring to the same instance of your DocName class (only create a new DocName() once in your code, and then pass that reference to both forms).

Form myForm1    = new Form();
Form myForm2    = new Form();
DocName dn      = new DocName();
myForm1.docName = dn;
myForm2.docName = dn;
dn.DoctName     = "SomeDocumentName.txt";

MessageBox.Show(myForm1.docName.DoctName);  // "SomeDocumentName.txt"
MessageBox.Show(myForm2.docName.DoctName);  // "SomeDocumentName.txt"

Because there is only one instance of your DoctName class, the property of that class will persist regardless of which form is calling it.

public string name; <--- name = "blah"; <--- extra code docname dc = new docname(); dc.Doctname = name;

Well, according to your code, the variable called "name" is null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM