Click here to Skip to main content
15,880,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have created a class as the following it has one global variable.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LankaLab
{
    class dbConnect
    {

        public String strSuperPatID;

        public String StrSuperPatID
        {
            get { return strSuperPatID; }
            set { strSuperPatID = value; }
        }

                     
         }
}


Now I have created another class and I have created an instance of the dbConnect class.

C#
 public partial class frmFulBldCuntDet : Form
{

  private dbConnect dbConn = new dbConnect();

 }


Now I want to set values to the global variable in the dbConnect class from the frmBldCuntDet class. I already created the getter() & setter() methods. But now I want to add values to the strSuperPatID from the frmBldCuntDet and display it from another class ( haven't created yet). All I need is to use getter() & setter(0 methods.

Thank You!

Moved to question from OP "solution" - OriginalGriff

frmBldCuntDet class has the following variables and those use to generate a automatic patient id.


C#
 Class - 01
            
            public partial class frmFulBldCuntDet : Form
    {
            private dbConnect dbConn = new dbConnect();

            private String strID;
            private String strPatID;

            private int intYear;
            private String strYear;

            private int intMonth;
            private String strMonth;

         private void btnPrint_Click(object sender, EventArgs e)
        {
            intYear = DateTime.Now.Year;
            strYear = intYear.ToString();
            intMonth = DateTime.Now.Month;
            strID = cmbPatID.Text;

//MyMethod() in use.
            MyMethod();

      frmHBAIC HbIAC01 = new frmHBAIC();

      HbIAC01.show(); 

       }
         /* This MyMethod will pass the value of strPatID to the global variable StrSuperPatID */
           private string MyMethod() {

            return(dbConn.StrSuperPatID = strPatID);
        
        }

    }

 Class - 02

  public partial class frmHBAIC : Form
    {

     private dbConnect dbConn = new dbConnect();

   /* When the button1 is clicked I want to display the value of StrSuperPatID (global variable) in a messagebox.*/
   // I tried this as the follwoing but it didn't happen!
      private void button1_Click(object sender, EventArgs e)
        {
          MessageBox.show(dbConn.StrSuperPatID);  
        }

    }

  Class - 03 - This class includes the global variables and getter & setter metohds of its'.

  class dbConnect
    {

        public String strSuperPatID;

        public String StrSuperPatID
        {
            get { return strSuperPatID; }
            set { strSuperPatID = value; }
        }

                     
         }


I cannot find the problem yet that preventing passing the values to the global variable.

Hope that you will help me

Thank You!
Posted
Updated 7-Apr-13 1:30am
v2
Comments
[no name] 7-Apr-13 7:35am    
It would appear to me that you are creating new instances of dbConnect and trying to show the value that is just the default value. You need to create a Singleton or pass an existing instance of dbConnect to your other classes.
Chiranthaka Sampath 7-Apr-13 8:42am    
Could you show me how to do the solution as mentioned you?
[no name] 7-Apr-13 11:34am    
Research "Singleton" or how to pass data as an argument to a method.

1 solution

First off, don't expose your backing fields!
Either use an automatic property:
C#
public String StrSuperPatID { get; set; }
or declare the backing field as private
C#
class dbConnect
{

    private String strSuperPatID;

    public String StrSuperPatID
    {
        get { return strSuperPatID; }
        set { strSuperPatID = value; }
    }
To use the getter and setter of the class instance is easy:

C#
public partial class frmFulBldCuntDet : Form
   {
   private dbConnect dbConn = new dbConnect();
   private void MyMethod()
      {
      dbConnect.StrSuperPatID = "Hello World!";    // Uses the setter
      ...
      Console.WriteLine(dbConnect.StrSuperPatID);  // Uses the getter
      }
   }


"It didn't help me to solve the problem. However I have placed the modified question as the solution 02 and hope it will describe my problem"

You are aware that C# doesn't have global variables? That everything is contained within a class? So if you want to access StrSuperPatID from a different class, you either need to access them via a class instance as shown above or make them static within the dbConnect class:

C#
class dbConnect
    {
    private static String strSuperPatID;
    public static String StrSuperPatID
        {
        get { return strSuperPatID; }
        set { strSuperPatID = value; }
        }
    }
And when I said "don't expose your backing fields!" why did you continue to do so? It defeats the purpose of having a property in the first place if the outside world can just modify the backing store directly!

"You have mentioned that "don't expose your backing fields!" does make it any sense that this is about encapsulation? Or other thing? can you explain it to me?"

Yes, it is about encapsulation!
When you declare a property, you are actually declaring two methods: the getter and the setter.
C#
string myString;
public string MyString
    {
    get { return myString; }
    set { myString = value; }
    }
Is the equivalent of:
C#
string myString;
public string GetMyString() { return myString; }
public void SetMyString(string value) { myString = value; }

The compiler adds some syntactic sugar to make them easier to use:
C#
MyString = "hello";
Console.WriteLine(MyString);
Instead of having to write:
C#
SetMyString("hello");
Console.WriteLine(GetMyString());
And properties look like "normal" variables, but they add the capability to validate data, put it into controls for display, or use something totally different instead - all without the user knowing about it.

When you expose your backing field (and that is just the name given to the class level variable you actually store the property value in: myString in the example I gave, and to expose it means to make it available outside the class by making it public for example) you let the user circumvent the mechanism altogether. If your property setter validates a string so that is it always a correct and valid UserName for example, then exposing the backing field lets the outside world bypass that validation and change the value to an invalid UserName without your class knowing about it. So you program falls over because your other code relies on the validation to ensure it doesn't need to check the value every time it uses it.

So if you declare both strSuperPatID and StrSuperPatIDas public then there is no point in having the property in the first place because the world outside your class doesn't have to use it.

Make your backing fields private and the outside world can't touch 'em except via the property where you control what happens! :laugh:


"Ok pal then what should I do? Please state the best practice! Thank You!"

Either you need the common variables to be static (and then it has a single instance, accessed via the class name rather than a variable) or you want the Parent (form1) do do the work. Personally, I would go with the parent in most cases, but in this specific case I would make the CommonVariable class static and use an automatic property (since you do nothing else with it than store the value).
C#
public static class CommonVariables
    {
    public static string StrSuperPatID {get; set;}
    }

You then access it via the class name.
Form1:
C#
private void button1_Click(object sender, EventArgs e)
    {
    CommonVariables.StrSuperPatID = strYear + strMonth + strID;
    frmHBAIC hbi01 = new frmHBAIC();
    hbi01.Show();
    }

and Form2:
C#
private void button1_Click_1(object sender, EventArgs e)
    {
    label1.Text = CommonVariables.StrSuperPatID;
    }
Without trying to declare a variable of the class CommonVariables in either form.
 
Share this answer
 
v4
Comments
Chiranthaka Sampath 7-Apr-13 7:22am    
It didn't help me to solve the problem. However I have placed the modified question as the solution 02 and hope it will describe my problem
OriginalGriff 7-Apr-13 7:38am    
Answer updated
Chiranthaka Sampath 7-Apr-13 8:38am    
You have mentioned that "don't expose your backing fields!" does make it any sense that this is about encapsulation? Or other thing? can you explain it to me?
OriginalGriff 7-Apr-13 9:01am    
Answer updated
Chiranthaka Sampath 10-Apr-13 5:23am    
Ok pal then how can I able to pass the value to a text box in another form?
I have tried that as the following
Form 1

private CommonVariables CV01 = new CommonVariables();

private void button1_Click(object sender, EventArgs e)
{
CV01.StrSuperPatID = strYear + strMonth + strID;

frmHBAIC hbi01 = new frmHBAIC();

hbi01.Show();
}

Form 02

private CommonVariables CV01 = new CommonVariables();

private void button1_Click_1(object sender, EventArgs e)
{
label1.Text = CV01.StrSuperPatID;
}

public class CommonVariables
{

private String strSuperPatID;

public String StrSuperPatID
{
get { return strSuperPatID; }
set { strSuperPatID = value; }
}

}

But when I click the Button at the Form 02 the label does not display the value! Have I done all the things correctly?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900