Search code examples
c#textbox

C# Get textBox value from another class


Let's say I have a form named Form1 with textBox and button in it.

I want to get the textBox value from another class on button click. I'm trying to do it like this, but it doesn't work:

class Main
{
    public void someMethod()
    {
        Form1 f1 = new Form1();
        string desiredValue = f1.textBox.Text;
    }
}

Forgive me for the dumb question, but I'm pretty new in C# and can't get this thing to work.


Solution

  • You need to find the opened Form1 instead of creating another Form1, create the following class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        class Class1
        {
            public void someMethod()
            {
                TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;
                Debug.WriteLine(t.Text + "what?");
            }
        }
    }
    

    Then in your button click method

    private void button1_Click(object sender, EventArgs e)
    {
        Class1 c = new Class1();
        c.someMethod();
    }