Normally you would pass it as an argument, for example:
void Method1() { var myString = "help"; Method2(myString); } void Method2(string aString) { var myString = "I need "; var anotherString = myString + aString; }
However, the methods in your example are event listeners. Usually you do not call them directly. (I suppose you can, but I never found an instance where you need to.) Thus, in this particular case, it would be wiser to store the value in a common place in the class for two methods. Something like that:
string StringA { get; set; } public void button1_Click(object sender, EventArgs e) { StringA = "help"; } public void button2_Click(object sender, EventArgs e) { string b = "I need "; string c = b + StringA; }
Note, however, that this will behave differently in ASP.NET. Therefore, if you use what you need, you probably want to take it one step further. The reason it behaves differently is because the server side is "stateless." Thus, each button click coming from the client will lead to a completely new instance of the class. Thus, if you set this class element in the first button event handler, it will not be displayed when it is used in the second button event handler.
In this case, you will want to view the state stored in the web application. Options include:
- Page values โโ(hidden fields, for example)
- Cookies
- Session Variables
- Application variables
- Database
- Server file
- Some other server-side storage methods, etc.
David source share