I'm relatively new to C#, having migrated over from C++, so I'm a little confused about the use of variables.
I have a class called User located in the program's main namespace
// In User.cs
namespace TestProgram
{
class User
{
public string name;
public int id;
public User()
{
name = "John Doe";
id = 0;
}
public void setName(string nName) // I know these two can be
{ // turned into C# style
name = nName; // with get and set
} // but one step at a time...
public string getName()
{
return name;
}
}
}
In the main file Program.cs, under the Main() function in the same namespace, I've got
User.mainUser = new User();
// This works fine and produces no errors.
// I can mess with the mainUser object just fine as long as I do so within Main()
Now using VS 2005's form generator I've put in a label, a textBox, and a button. I'd like it to, when the button is clicked, take textBox1.Text's value, change mainUser's name to that value, and then change the label to the name as well. All that is in Form1.cs as generated by VS.
So my problem/question is basically that the button1_Click(...) function, which is located in the partial class Form1 in the same namespace TestProgram, cannot find that declared mainUser and therefore cannot get/set any of its values.
// In Form1.cs
// namespace TestProgram -> public partial class Form1 : Form -> private void button1_Click
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text != "")
{
mainUser.setName(textBox1.Text); // doesn't work
label1.Text = mainUser.getName(); // also doesn't work
}
}
// One error for each mainUser entry:
// "The name 'mainUser' does not exist in the current context."
So how do I pass that mainUser object to Form1's button1_Click(...) or any Form components?