1

I've created a textbox and want to reference it in a static methd. how can I do that? here;s my code

    private void Form1_Load(object sender, EventArgs e)
    {
        TextBox textbox2 = new TextBox();
        textbox2.Text = "A";
    }

    static void gettext() 
    {
        textbox2.Text = "B"; //here is my problem
    } 
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
user1853846
  • 55
  • 1
  • 3
  • 9

5 Answers5

6

You would need to pass it into the static method somehow, easiest option is to just expand the method signature to accept the textbox:

static void gettext(TextBox textBox) 
{
    textBox.Text = "B"; //here is my problem
} 
Lloyd
  • 29,197
  • 4
  • 84
  • 98
4

You should give your textbox as a parameter to the static method

static void gettext(TextBox textbox)
{
    textbox.Text = "B";
}
Nolonar
  • 5,962
  • 3
  • 36
  • 55
2

I'm not sure you understand what static means, static means that it belongs to the CLASS not an INSTANCE of the class. Possibly a better solution to your problem would be to create an instance method which set the text.

// private variable
private TextBox textbox2;

private void Form1_Load(object sender, EventArgs e)
{
    // refers to private instance variable
    textbox2 = new TextBox();
    textbox2.Text = "A";
}

private void gettext() 
{
    // refers to private instance variable
    textbox2.Text = "B";
} 

If you're having difficulty understanding static, odds are you don't need to use it. Static members are available to all instances of a class but don't belong to any of them, which means static methods cannot access private members.

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • 1
    Why did this get downvoted? It doesn't make use of `static` methods, but as far as I can see, this is a totally valid answer, am I missing something? – Nolonar Mar 11 '13 at 10:47
  • 1
    also not sure why (it is not directly answering the explicit question, yes, but it certainly gives what is likely the best and most useful answer, in my mind) +1 – Kevin Versfeld Mar 11 '13 at 10:52
2

You can do so

static void gettext(TextBox textbox2) 
{
    textbox2.Text = "B";
} 

And in code

private void Form1_Load(object sender, EventArgs e)
{
    YourClass.gettext(textbox2);
}
Alex
  • 8,827
  • 3
  • 42
  • 58
-1

You can create a static variable set on Load :

private static readonly TextBox _textBox = new TextBox();

private void Form1_Load(object sender, EventArgs e)
{
    _textBox.Text = "A";
}

static void gettext()  
{ 
    _textbox2.Text = "B";
} 
Toto
  • 7,491
  • 18
  • 50
  • 72
  • The textBox is readonly and never reassigned, only the Text property. If you prefer, you remove the readonly and create the TextBox on the Load method. – Toto Mar 11 '13 at 13:08