How do I pass variables between methods in C#? [duplicate] - c#

This question already has answers here:
Use a variable from another method in C#
(2 answers)
Closed 2 years ago.
I am trying to build a program, but I realized I can't access a certain variable because it's created in another method.
How do I transfer a variable to another method?
This is an example of what I'm trying to do:
namespace Example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
}
private void label1_Click(object sender, EventArgs e)
{
// Get the "text" variable and use it
label1.Text = text;
}
}
}

Your example has a Form named Form1 that has a Button named button1, a TextBox named textbox1 and a Label named label1.
The scenario you are attempting is:
user enters some text into textbox1
user clicks on button1, this will save the current value from textbox1
user clicks on label1, this will display the value that was stored in the previous step
It is important to understand that in this scenario we are not trying to pass a value between 2 methods because the button click and the label click can occur independently of each other, so really this is like the memory store (M+) and memory recall (MR) buttons on calculator.
To achieve this storage you should create an instance variable (sometimes referred to as a member variable) on the Form1 class, this will be accessible to the other methods on the same instance of the Form1 class.
See Working with Instance and Local variables for a practical explanation
Create a field or a property to store the value, for your specific example either would work, however to become familiar with C# techniques I would recommend you start with a property, as that better encapsulates your scenario of storing the value for later use and later to potentially augment how and where the value is actually stored.
See What is the difference between a field and a property?
for a healthy discussion
Until you need to change the implementation, you can simply use an Auto-Property
public string StoredText { get; set; }
Now in the click event handler of button1 we can set the value of the StoredText property on the Form1 instance
private void button1_Click(object sender, EventArgs e)
{
this.StoredText = textBox1.Text;
}
set is a term we use for saving a value into a property in c#
Note the use of the this keyword, it is optional in this case, or can be inferred by the compliler, it indicates that we want to reference a member on the instance of the class, not a variable that might have the same name within the same method scope of the line of code that is executing.
Finally in the click event handler of label1 we can get the value that was previously stored in the StoredText property in the Form1 instance.
private void label1_Click(object sender, EventArgs e)
{
// Get the "StoredText" variable and use it
label1.Text = this.StoredText;
}
get is a term we use for accessing a value from a property in c#
this is not required, but can be helpful to understand that we are accessing a member that is outside of the current method scope.
Together this looks something like:
namespace Example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>Saved value from see <see href="textBox1"/></summary>
public string StoredText { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.StoredText = textBox1.Text;
}
private void label1_Click(object sender, EventArgs e)
{
// Get the "StoredText" variable and use it
label1.Text = this.StoredText;
}
}
}
What you may not have noticed is that textBox1 and label1 are themselves infact instance variables that are initialized in a separate code file when InitializeComponent() is executed in the constructor.
For this reason you do not need to store the value at all and you could simply re-write the client event handler for button1 to write directly to label:
label1.Text = textBox1.Text;
It is possible to pass variables directly between methods without an intermediary store, this is a lesson for another day and will involve return statements and/or parameters on your methods.
In this scenario however, neither return or additional parameters on these methods cannot be used because these are event handlers that need a specific method signature to operate as expected.

You are almost there. It is a common practice in object-oriented programming to have private variables in a class, in order to share states. Add a variable in your class. It will be available in all methods and can be used to shared data between them (this is one approach of many):
namespace Example
{
public partial class Form1 : Form
{
private string inputText { get; set; }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
inputText = textBox1.Text;
}
private void label1_Click(object sender, EventArgs e)
{
// Get the "text" variable and use it
label1.Text = inputText;
}
}
}

Related

Access object from another button click event [duplicate]

This question already has answers here:
The name 'str' does not exist in the current context
(2 answers)
Use a variable from another method in C#
(2 answers)
Closed 5 years ago.
I'm fairly new to C# so this might be pretty simple actually though I have spent a couple hours searching without a solution.
I'm working with windows form and I am trying to access an object from another button-click event. The error I'm getting is "The name 'object' does not exist in the current context" when trying to access object in Button2_Click.
public void Button1_Click(object sender, EventArgs e)
{
// Prefilled with a persons info
MyClass object = new MyClass();
}
public void Button2_Click(object sender, EventArgs e)
{
// Access object
string name = object.Name;
}
So my question is how do I access an object created in another "Button_Click"?
A couple of issues exists.
You can't use object as variable name. (object is a reserved keyword)
You can't access a internal variable, within another event.
To solve your issue, you would scope the variable when your initial object is created.
public class Example
{
// Variable declared as a class global.
private readonly Sample sample;
// Constructor to build our sample.
public Example() => sample = new Sample();
// Button writing a property from sample.
protected void btnSend(object sender, EventArgs e) => Console.WriteLine(sample.SomeProperty);
}
So the object is in the upper portion of your class, when you build Example, a sample is always created. So as you utilize Sample within your Example class, it will be correctly scoped.
I also don't understand why you have to click one button, to populate this object, so I altered to have the object built once Example is created.
The scope of the object should be class level in order to be used by other methods in the same class:
private MyClass _myClassObject; // class level object. Remember "object" is reserved keyword that is why renamed it to "_myClassObject"
public void Button1_Click(object sender, EventArgs e)
{
// Prefilled with a persons info
_myClassObject = new MyClass();
}
public void Button2_Click(object sender, EventArgs e)
{
// Access object
string name = _myClassObject.Name;
}

How do I change the value of form controls without triggering any event?

I want to change the value that is assign to control of a form in c# (visual studio 2010), while the form is loaded.
I want my form should display to the end user, but at the same time as I get the data from server, I want it to reflect the same data onto the controls. (without any using timer, thread or any event).
Example : textBox1.text ="abc";
if server is sending "xyz" than while form is already loaded testbox's value should automatically change to xyz.
without any click or any kind of event.
You have to look at how Properties in c# work:
If we decompile a simple class on sharplab.io
public class C {
public int foo
{get;set;}
}
You will see that the compile will always generate backing fields and a getter and setter method.
So if you don't want to trigger an event you will have to bypass these methods as most likely the event will be triggered in there.
This should be doable with an reflection which is normally pretty easy to do.
BUT Textbox doesn't seem to have a backing field which is easily accessible for its Text-Property. Most likely it is set by its private StringSource field. Which is from the internal type StringSource. So first we have to get the type. Get a reference to the constructor then call this and set the private field.
This is how far i've come:
private int number = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
number++;
this.textBox1.Text = number.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
number++;
Type cTorType = typeof(string[]);
string[] cTorParams = new string[] { number.ToString() };
Type type = this.textBox1.GetType().GetRuntimeFields().ElementAt(11).FieldType;
ConstructorInfo ctor = type.GetConstructor(new[] { cTorType });
object stringSourceInstance = ctor.Invoke(new[] { cTorParams });
this.textBox1.GetType().GetRuntimeFields().ElementAt(11).SetValue(this.textBox1, stringSourceInstance);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("Changed!");
}
I'd recommend digging a bit more into reflection and see what you can find in the TextBox class by using typeof(TextBox).GetFields / .GetProperties because somewhere there must be a field or property which you can change to bypass your setter method triggering the event.
Hope this helps.

c# accessing string from method1 in method2, after method1's execution

I'm working on a form with one textbox, one button, one combobox and a couple of other textboxes.
So, I want this winforms program to work as follows:
1) you fill in a database index value in textbox1 (example: 22222)
2) you click the button. This button goes to the database, looks up the value in textbox1 and eventually creates a string based on what the database returns. (example: returned value = super; string value = 5)
3) After you've clicked the button, you should be able to fill in the other textboxes depending on the SelectedIndex of the combobox. The values filled in in the combobox are completely dependant on the value of the string generated by button1. (example: combobox1 selectedindex = 1: textbox2.text = S; combobox selectedIndex = 2: textbox3.text = U)
So, basically, button1 must first be executed before combobox1 can even begin to execute itself. Also note that there are (at least) two methods used here: a void for button1_click and a void for combobox1_selectedindexchanged.
The two first parts are done. What I'm having trouble with is accessing the string generated by button1, which is only accessible after its execution, and using it in combobox1's method.
Is this possible?
create a property on your Form class which is populated once the button 1 is clicked with the value from your textbox.
then simply use it whenever and however you need.
example code :
public partial class Form1 : Form
{
public string Value;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Value = textBox1.Text;
textBox2.Text = this.Value;
}
}
Thanks for the help!
I was eventually able to do it like this, to truly access the variable inside the scope of method2, while it was created in method1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string output = "test";
File.WriteAllText(#"C:\output.txt", output)
}
private void combobox1_SelectedItemChanged
{
string output = File.ReadAllText(#"C:\output.txt")
// do something with this string
}
}

Passing object to different windows forms

I want to pass a C# object between win forms. At the moment, I have setup a basic project to learn how to do this which consists of two forms - form1 and form2 and a class called class1.cs which contains get and set methods to set a string variable with a value entered in form1. (Form 2 is supposed to get the value stored in the class1 object)
How can I get the string value from the object that was set in form1? Do I need to pass it as a parameter to form2?
Any comments/help will be appeciated!
Thanks,
EDIT: Here's the code I have at the moment: (form1.cs)
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
Class1 class1 = new Class1();
class1.setStringValue(textBox1.Text);
}
}
}
}
There are a few different ways to do this, you could use a static class object, the above example would be ideal for this activity.
public static class MyStaticClass
{
public static string MyStringMessage {get;set;}
}
You don't need to instance the class, just call it
MyStaticClass.MyStringMessage = "Hello World";
Console.WriteLine (MyStaticClass.MyStringMessage);
If you want an instance of the object you can pass the class object that you create on Form1 into Form2 with the following.
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.MyClass = class1;
form2.Show();
}
Then create a property on Form2 to accept the class object.
public Class1 MyClass {get;set;}
remember to make the Class1 object a global variable rather than create it within button 2 itself.
Yes, in Form1 you declare an instance of Class1 and then set the parameters as needed, then you pass it to Form2. You could for example have a constructor in Form2 and have a Class1 parameter in it. Assuming that Form1 creates Form2, otherwise you have to have some way for Form1 to find Form2 to pass the instance across.
Since I have been working in ASP.Net the last couple years I have found myself working with Newtonsoft.Json a lot. Turns out to be great within WinForms too, and in this case seemed to simplify passing objects between forms... even complex ones are a breeze!
The implementation is like this:
// Set Object Property within Form
public partial class FlashNotify : Form
{
public string Json { get; set; }
}
On the form load event you can then grab your object:
private void FlashNotify_Load(object sender, EventArgs e)
{
// Deserialize from string back to object
CommUserGroupMessage msg = new CommUserGroupMessage();
msg = Newtonsoft.Json.JsonConvert.DeserializeObject<CommUserGroupMessage>(Json);
}
Lastly is passing the object to the form:
// Serialize the Object into a string to pass
string json = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
FlashNotify fn = new FlashNotify();
fn.Json = json;
fn.Show();
Granted the original selected answer is probably easier, however I like this approach as it avoids the need to replicate the class within your form, which I think makes it easier to maintain (Correction: Miss correctly read the static class in the example, I at first thought it was replicated within the form).
Using Delegate you can easily pass data to a form.
Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type
Step 1
Add a delegate signature to form1 as below:
public delegate void delPassDataToFrom(Object obj);
Step 2
In form1’s any button click event handler, instantiate form2 class and delegate. Assign a function in form2 to the delegate and call the delegate as below:
private void btnSend_Click(object sender, System.EventArgs e)
{
Form2 frm = new Form2();
delPassDataToFrom del = new delPassDataToFrom(frm.retrieveData);
del(objectToPass);
frm.Show();
}
Step 3
In form2, add a function to which the delegate should point to. This function will use the object passed:
public void retrieveData(Object objPassedFromParent)
{
//use the objPassedFromParent object as needed
}

How to change text in a textbox on another form in Visual C#?

In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to do this before showing the form, but I get an error saying the textbox is inaccessible due to its protection level.
How can I set the textbox in a form before I show it?
private void button2_Click(object sender, EventArgs e)
{
fixgame changeCards = new fixgame();
changeCards.p1c1val.text = "3";
changeCards.Show();
}
When you create the new form in the button click event handler, you instantiate a new form object and then call its show method.
Once you have the form object you can also call any other methods or properties that are present on that class, including a property that sets the value of the textbox.
So, the code below adds a property to the Form2 class that sets your textbox (where textbox1 is the name of your textbox). I prefer this method method over making the TextBox itself visible by modifying its access modifier because it gives you better encapsulation, ensuring you have control over how the textbox is used.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string TextBoxValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
And in the button click event of the first form you can just have code like:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.TextBoxValue = "SomeValue";
form2.Show();
}
You can set "Modifiers" property of TextBox control to "Public"
Try this.. :)
Form1 f1 = (Form1)Application.OpenForms["Form1"];
TextBox tb = (TextBox)f1.Controls["TextBox1"];
tb.Text = "Value";
I know this was long time ago, but seems to be a pretty popular subject with many duplicate questions. Now I had a similar situation where I had a class that was called from other classes with many separate threads and I had to update one specific form from all these other threads. So creating a delegate event handler was the answer.
The solution that worked for me:
I created an event in the class I wanted to do the update on another form. (First of course I instantiated the form (called SubAsstToolTipWindow) in the class.)
Then I used this event (ToolTipShow) to create an event handler on the form I wanted to update the label on. Worked like a charm.
I used this description to devise my own code below in the class that does the update:
public static class SubAsstToolTip
{
private static SubAsstToolTipWindow ttip = new SubAsstToolTipWindow();
public delegate void ToolTipShowEventHandler();
public static event ToolTipShowEventHandler ToolTipShow;
public static void Show()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = true;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
public static void Hide()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = false;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
}
Then the code in my form that was updated:
public partial class SubAsstToolTipWindow : Form
{
public SubAsstToolTipWindow()
{
InitializeComponent();
// Right after initializing create the event handler that
// traps the event in the class
SubAsstToolTip.ToolTipShow += SubAsstToolTip_ToolTipShow;
}
private void SubAsstToolTip_ToolTipShow()
{
if (Vars.MyToolTipIsOn) // This boolean is a static one that I set in the other class.
{
// Call other private method on the form or do whatever
ShowToolTip(Vars.MyToolTipText, Vars.MyToolTipX, Vars.MyToolTipY);
}
else
{
HideToolTip();
}
}
I hope this helps many of you still running into the same situation.
In the designer code-behind file simply change the declaration of the text box from the default:
private System.Windows.Forms.TextBox textBox1;
to:
protected System.Windows.Forms.TextBox textBox1;
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member (for more info, see this link).
I also had the same doubt, So I searched on internet and found a good way to pass variable values in between forms in C#, It is simple that I expected. It is nothing, but to assign a variable in the first Form and you can access that variable from any form. I have created a video tutorial on 'How to pass values to a form'
Go to the below link to see the Video Tutorial.
Passing Textbox Text to another form in Visual C#
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
TextBox txt = (TextBox)frm.Controls.Find("p1c1val", true)[0];
txt.Text = "foo";
}

Categories

Resources