none
Accessing variable input in A.cs in B.cs RRS feed

Answers

  • Is this the sort of thing you're after?

    public class MainForm : Form
    {
       void ShowChild ( )
       {
          string someValue = SomeMethodToGetThevalue();
          ChildForm child = new ChildForm(somevalue);
          child.ShowDialog();
       }
    }
    
    public class ChildForm : Form
    {
    
       public string SomeValue {get; private set; }
    
       public ChildForm(string someValue)
       {
          SomeValue = someValue;
       }
    }


    • Edited by Ante Meridian Tuesday, October 31, 2017 2:03 AM typo.
    • Marked as answer by Dankoh97 Thursday, November 2, 2017 7:25 AM
    Tuesday, October 31, 2017 2:02 AM

All replies

  • Hi Dankoh97,

    from the description of the thread, it looks like your issue is more related with C# development.

    on this forum, we only handles the Excel Development related issues.

    so for better response and better solution for your issue, I move this thread to Visual C# forum.

    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us.

    Thank you for your understanding.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 30, 2017 2:50 AM
  • Hello,

     I think you need to show us code and give more details about the textBox.

    Like, on the same Form, two independent Forms, or Parent/Child Form scheme.

    The more details about the input and expected output of your project then the

    more we can help.

     Thanks :)

    Monday, October 30, 2017 12:05 PM
  • You cannot expose a variable in a method to another class. Variables in methods are local and go away when the method terminates. You'll need to promote the variable up to a property. This, of course, also assumes that you wouldn't directly expose any UI elements as that is bad form.

    public class MainForm : Form
    {
       void ShowChild ( )
       {
          var child = new ChildForm();
          child.ShowDialog();
    
          //Get value
          var value = child.SomeValue;
       }
    }
    
    public class ChildForm : Form
    {
       //Assuming no one outside form should be able to 
       //get it
       public string SomeValue {get; private set; }
    
    
       private void SomethingHappenedInUI ()
       {
          //Get or calculate some value
          SomeValue = "Hello";
       }
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, October 30, 2017 2:58 PM
    Moderator
  • For your answer. The MainForm opens the ChildForm in order to obtain the value and store it right? However in my program, the ChildForm in your example is actually the InitialForm, basically in your example it would mean that after some functions are performed  in the ChildForm then the MainForm will appear.

    Assuming I don't use Aform to open Bform at the same time is there a way to transfer the value over?

    Tuesday, October 31, 2017 1:30 AM
  • Is this the sort of thing you're after?

    public class MainForm : Form
    {
       void ShowChild ( )
       {
          string someValue = SomeMethodToGetThevalue();
          ChildForm child = new ChildForm(somevalue);
          child.ShowDialog();
       }
    }
    
    public class ChildForm : Form
    {
    
       public string SomeValue {get; private set; }
    
       public ChildForm(string someValue)
       {
          SomeValue = someValue;
       }
    }


    • Edited by Ante Meridian Tuesday, October 31, 2017 2:03 AM typo.
    • Marked as answer by Dankoh97 Thursday, November 2, 2017 7:25 AM
    Tuesday, October 31, 2017 2:02 AM
  • public class Form2 : Form { void form2 ( ) { string someValue = SomeMethodToGetThevalue(); form1 useForm1 = new form1(somevalue); //No showdialog as Form1 leads to Form2, there shouldn't be Form 1 opening again. //use SomeValue from form1 HERE } } public class Form1 : Form { public string SomeValue {get; private set; } public form1(string someValue) { SomeValue = ("a string") //obtaining a value here and assign it to variable } }

    This is what i'm after. Simply want to get a value obtained in Form1 to be used in Form2. However both forms will not be active at the same time, when Form1 closes, Form2 opens
    • Edited by Dankoh97 Tuesday, October 31, 2017 7:13 AM
    Tuesday, October 31, 2017 7:13 AM
  • Since SomeValue is public you can simply reference it.

    useForm1.SomeValue

    But I suspect that this isn't going to solve your problem. You didn't specify how form1 is opened. Nor did you clarify how form2 is getting closed. Without that information we're just guessing. I really wonder if you're actually trying to solve a problem that doesn't exist. You're trying to relate forms visible on the screen with the lifetimes of the form variables and they are unrelated. You can have a form variable that is never shown on the screen. For more complicated apps you probably wouldn't even close the form. You'd just hide it. In all cases though both forms are still available, just not visible.

    But if you really need to persist data across 2 forms that have completely different lifetimes then you have to store the data in another instance. It completely depends upon the circumstances and how much data you're storing but you might use a simple static variable somewhere, a service class, a completely separate manager class or (for longer term) a file or database. Without any additional information we aren't going to be able to help you better than that.


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, October 31, 2017 1:59 PM
    Moderator
  • Sorry, but I'm still struggling to understand what you're after.

    Maybe statics are the answer. You can create a static class to hold data that you want to access from other classes. Here's a general example written as a console app. If you think of the classes C1 and C2 as being like Form1 and Form2, it should give you the idea.

    using System;
    using System.Text;
    using System.IO;
    
    namespace ConsoleApplication1
    {
       class Program
       {
          static void Main(string[] args)
          {
             // Set the static value.
             C1 c1 = new C1();
    
             // Print the value that C1 just set, then change it.
             C2 c2 = new C2();
    
             // Back in C1, print the value set by C2.
             c1.PrintCurrent();
          }
       }
    
       /// <summary>
       /// A test class. The constructor sets the static value.
       /// </summary>
       public class C1
       {
          public C1()
          {
             Globals.SomeValue = "Hello";
          }
    
          public void PrintCurrent()
          {
             Console.WriteLine(Globals.SomeValue);
          }
       }
    
       /// <summary>
       /// Another test class. The constructor prints the static value, then changes it.
       /// </summary>
       public class C2
       {
          public C2()
          {
             // Print the current value, then change the value.
             Console.WriteLine(Globals.SomeValue);
             Globals.SomeValue = "World.";
          }
       }
    
       /// <summary>
       /// A static class to hold data we want to be in common for all classes.
       /// </summary>
       public static class Globals
       {
          public static string SomeValue { get; set;}
       }
    }
    

    Tuesday, October 31, 2017 10:49 PM
  • Hi, sorry for not clarifying my problem as I am new to programming but am however required to make a program for internship. Form1 is opened at the beginning when you open the application and it has a login function. After logging in, Form1 is hidden and Form2 is shown. I need to get a value obtained from a textbox in Form1 and use it in a function in Form2. Hope this clarifies :)
    Wednesday, November 1, 2017 3:53 AM
  • In that case I assume that the closing of form1 and opening of form2 are either happening in the same method or at least in the same class, a simple local variable can transition the value.

    public class LoginForm : Form
    {
       //Probably backed by a UI element
       public string UserName { get; set; }
    }
    
    public class MainForm : Form
    {
       //Making something up here to represent data
       //that needs to transition from login form to here
       public string CurrentUser { get;set; }
    }
    
    //Code that is responsible for closing form1 and opening form2
    void Login ( LoginForm form1 )
    {
       //Get the current value from form1
       var user = form1.UserName;
    
       //Open form2
       var form2 = new MainForm();
     
       //Associate form1's data with form2
       form2.CurrentUser = user;   
    }
    If no code has access to both forms at the same time and cannot persist the data in a field or local variable then you're only choice is to create a helper class that can be used by both forms and is responsible for storing the data that both forms need.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 1, 2017 4:50 AM
    Moderator
  • Yes no code has access to both forms. The Login form hides itself and shows Main form based on a "if" statement located in one of the functions of the Login form (e.g if (something here) then Login.hide(); and Main.show()).

    How can a helper class be created and used to pass the value obtained in Login form to the Main form?

    Wednesday, November 1, 2017 8:36 AM
  • "The Login form hides itself and shows Main form based on a "if" statement located in one of the functions of the Login form (e.g if (something here) then Login.hide(); and Main.show())."

    But that method then has access to both forms doesn't it?

    public class LoginForm : Form
    {
       void ShowMainForm ()
       {
          //not sure where Main comes from but...
          Main.SomeProperty = someValueFromLoginForm;
          Main.Show();
       }
    }
    
    public class MainForm : Form
    {
       public string SomeProperty { get;set; }
    }

    A helper class can be used when the data isn't tied to a particular form. If you think about the currently logged in user, they aren't really tied to a UI element but by the process (or thread) they are running as. Therefore a helper class is the best place to store this information. 

    public class UserService
    {
       public User CurrentUser { get;set; }
    }

    How you get access to this class is completely dependent upon your application architecture. If you're using DI then it would be part of the dependencies your login and form class take.

    public class LoginForm : Form
    {
       //This would break the designer, but you get the idea
       public LoginForm ( IUserService userService )
       { 
          _userService = userService;
       }
    
       void Login ()
       {
          //Sets the current user if login successful
          _userService.Login(someValueWithUserName);
       }
    
       private readonly IUserService _userService;
    }
    
    public class MainForm : Form
    {
       //This would break the designer, but you get the idea
       public MainForm( IUserService userService )
       { 
          _userService = userService;
       }
    
       void GetUser ()
       {
          var user = _userService.CurrentUser;
       }
    
       private readonly IUserService _userService;
    
    }

    For this to work you'd have to define an interface that the helper class implements. You'd also need to ensure that the DI container you're using returns back the same instance in all cases (that depends on the DI container you're using).

    If you aren't using DI then a poor man's DI would work as well using a singleton of the helper class. If you don't even want to go that far then a static class would work as well, it is just really limiting. ASP.NET went that route with their Membership API. 


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 1, 2017 2:00 PM
    Moderator
  • Actually my forms are opened like this, the Login Form is just initialized and shown from the start so there is no method that is used to call it out. it's just there.

    then for the function:

     private void button1_Click(object sender, EventArgs e)
     {
             //some code here
             if (something)
             {
                 this.Hide();
    
                 Main main = new Main();
                 main.Show();
             } 
    does this mean that the method has access to both forms?

    Thursday, November 2, 2017 12:55 AM
  • C# scoping rules always apply. Given your above button1_click code, it seems like it is being called inside Login form. Therefore, during that method call, you have access to all the fields of Login and any public members of main (because you created an instance of it). So, as I demonstrated in an earlier posting, you can set the public property(ies) of your Main form to any fields of the Login form prior to showing the main form.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 2, 2017 1:35 AM
    Moderator
  • private void button1_Click(object sender, EventArgs e) { //some code here if (something) { this.Hide(); string data = SomeMethodToGetTheDataFromTheTextBoxOrWhatever(); Main main = new Main(data); main.Show(); } } public class Main : Form // 'Main' is a terrible name for a Form, but never mind. { // The data we want to get from the login form. string Data;

    // Make the required data an argument to the constructor. public Main(string data) { // Set the data we want from the login form here. // Now we can use it anywhere in this class. Data = data; } }


    Which is exactly what I was suggesting in my first post in this thread.

    Thursday, November 2, 2017 1:42 AM
  • Hi! I was abit confused about your code at first and how to implement it into my program but it works now thanks!
    Thursday, November 2, 2017 7:25 AM