C # Get textBox value from another class

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

I want to get the textBox value from another class on button click. I am 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 to C # and can't seem to get this to work.

+3


source to share


7 replies


You need to find open 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 the button click method

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

      

+13


source


your textBox is probably, private

although it should. If you need text from a textbox, you can open it with the property



public string TextBoxText{ get { return textBox.Text; } }

      

+5


source


When you speak

Form1 f1 = new Form1();

      

You are creating a whole new object with your own text box.

If you want the value that is in that text box of this form, you will need to refer to the same instance of Form1 where the user typed the value.

+2


source


I think this is because you are creating a new instance of form1, which is why you are actually getting the textbox from f1.

+1


source


Is this pseudo code, or is this the code you are actually trying to use?

If you are trying this code, what you are doing is creating a new Form1. If Form1's constructor doesn't put something in your textbox, it will be empty at that point.

0


source


I want to do something like this, but with a timer ... help please, I tried to edit the below code but it doesn't work.

Timer u = Application.OpenForms ["Form1"]. Controls ["SpeakTime"] as a Timer;

0


source


Form 1

public string pathret()
{
    return textBox.Text;
}

      

Form 2

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

      

0


source







All Articles