How to get data from other class in C#

catalina beaver 41 Reputation points
2022-06-07T08:20:14.707+00:00

Hi,
I'm new to C#. I have two pages in my UWP app. I need to get a data from a variable of other class(page). I always get zero when I try to read the variable. Please have a look at my below code.

namespace PROJECT
{
public sealed partial class MainPage : Page
    {
      public static int var;  // data stores in this variable. 

      public MainPage()
        {
           this.InitializeComponent();
        } 
        public void function()
        {
            var = 4;
        }
    }
}

In the above class. The variable var will set with the value 4. I want to get this data as soon as I navigate to other page. The other class is like below.

namespace PROJECT
{
public sealed partial class SecondPage : Page
    {

      public SecondPage()
        {
           this.InitializeComponent();
           int data = MainPage.var;
          System.Diagnostics.Debug.WriteLine(data); // here I always get 0

        } 
        public void function_secondpage()
        {
             int data = MainPage.var;
             System.Diagnostics.Debug.WriteLine(data); // here I get 4
        }
    }
}

I need to get the data from variavle var as soon as I navigate to the second page. I need to show that data on the second page. However, I always get 0.
I could read the data from the variable var correctly when I call the function function_seconfpage(). However, this wont help me. How can I read the data from varaible var successfully when I navigate to the second page?. Thank you in advance.

Developer technologies Universal Windows Platform (UWP)
Developer technologies C++
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-06-07T08:40:01.9+00:00

    Use a overload for the constructor

    namespace PROJECT
    {
     public sealed partial class SecondPage : Page
     {
     private int _initialValue;
    
           public SecondPage()
           {
                this.InitializeComponent();
    
    
           } 
     public SecondPage(int inComing)
     {
     this.InitializeComponent();
     _initialValue = inComing;
    
               System.Diagnostics.Debug.WriteLine(inComing); // here I always get 0
    
           } 
           public void function_secondpage()
           {
     System.Diagnostics.Debug.WriteLine(inComing); // here I get 4
           }
         }
    }
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.