0

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#.

4

2 回答 2

2

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.

于 2013-07-07T18:41:25.383 回答
0

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.

于 2013-07-07T18:17:36.300 回答