-1

Please be patient with me, I am new to C# and I am trying my best

so my question is, when we create a button in windows form app (wfa), there is a private event automatically created if you double click the button.

let's say we have 2 buttons (btn1 & btn2) btn1 click event has variable of type string called access and I need to call this variable in btn2 click event

so how we will pass the info from a private event to another ! enter image description here

private void button1_Click(object sender, EventArgs e)
{
    string access1 = "access 1";
}

private void button2_Click(object sender, EventArgs e)
{
    string access2 = access1;
}
taha
  • 722
  • 7
  • 15
  • 1
    the laziest solution would be to move the `access1` declaration up as class property. also, post the error message as text - its much preferred. – Bagus Tesa Dec 11 '22 at 00:23
  • it is not only a declaration , I just put a simple example . but it is a full code and this code should return some value to the variable and I can not put it in the main fram cuz it is executed every time I run the app which will make the app run time take long time – M.Mazzaz Dec 11 '22 at 18:31
  • my suggestion is just to make the `access1` available on `Btn2` scope. there are many ways, the more complicated one would be just to pull your entire logic out of the form code and create additional manager/service/repository class for any data-related stuff so both button can access them. the form will only concerned about presenting stuff. if you could provide more context, preferrably a [mcve] that would be **more helpful** really. – Bagus Tesa Dec 11 '22 at 23:01

1 Answers1

2

You can make the info a field instead of a local variable:

string access1 = "access 1";

private void button1_Click(object sender, EventArgs e)
{
            
}

private void button2_Click(object sender, EventArgs e)
{
    string access2 = access1;
}

Or use a property: What is the difference between a field and a property?

taha
  • 722
  • 7
  • 15
  • 1
    Your code example does not feature a property. Fields are not properties, and properties are not fields... –  Dec 11 '22 at 00:26
  • You are right, in my code example "access1" is a field, not a property, as explicated here: https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property. – Guilherme Djrdjrjan Santos Dec 11 '22 at 00:31
  • 1
    Yes, and you introduce your code example like "_You can **make the info a property** instead of a local variable:_". As the asker is clearly a C# rookie, it's not making it easier for them to learn the ropes if an answer confuses fields with properties. –  Dec 11 '22 at 00:36
  • this will not help, there is a full code shall be excuted only if I clicked the button and this code will return some value these value I need it to be used in another button . which in my case if it is a private it will not work – M.Mazzaz Dec 11 '22 at 18:32