Domanda

Been working on a simple c# windows app program. I have been able to pass a few variables from one form to the next and use them using form2 y = new form2(passingVariable); y.ShowDialog(); and then on the next form public form2(string myVariable). However this method only allows me to use the variable within those curly braces. Currently I am trying to pass it to the next form in line. However it won't let me use the variable when I try to pass it into the next form using the code line I provided above. It gives me the error The name 'userName' does not exist in the current context I have a lot of source code and didn't know what exactly was needed for me to share so here is the link to my webng.com account with a very simple web page set up with my source code if anyone needs to review it.

È stato utile?

Soluzione

Try creating another variable on that current form to store that Username and then assign the username passed into that variable. Your constructor will be like this then:

private string username;

public talkingWithProgram(string userName, string pcName)
{
InitializeComponent();
this.Text = pcName;
programQuestion.Text = "Whatcha wanna talk about \n" + userName + "?";
this.userName = userName;
}

sportsCategories y = new sportsCategories(userName);

Creating a new sportsCategories class now passes userName from this context, which has the value from the previous form. Currently it looks like you're referring to the userName in the constructor which is in the method context and out of scope outside.

Altri suggerimenti

I would avoid setting specific variables in the constructor of a windows form. In general, it is more customary to use getters and setters, or a function designated specifically for this purpose.

For example: If you can have the code form2 y = new form2(passingVariable); instead you can have the code

form2 y = new form2();
form2.SetMyVar(passingVariable);

OR, if you are using getters and setters:

form2 y = new form2();
form2.SetMyVar = passingVariable

That way, whenever you need to set or update the variable you can do it as long as you have a reference to the form. Also, in said SetMyVar() function (if you choose that method), be sure to set a class variable. In your code, class variables go outside your functions, so that they are visible to all functions of that instance of the class.

initialize a variable in a class xyz assign the values to them in constructor like

 String a1,b1=String.empty
  Class xyz
 {
   xyz(string a,string b)
  {       //constructor
   a1=a;
   b1=b;
    //Now use them in whole class
  }

 }

or if you want to use them in whole application then initialize them globally in Program.cs then you can set and get values like

Program.a1="abc"    //assigning value
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top