Kirev
Kirev

Reputation: 147

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.

Upvotes: 3

Views: 33053

Answers (6)

Al-Ameen Coe
Al-Ameen Coe

Reputation: 1

Form 1

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

Form 2

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

Upvotes: 0

daniloquio
daniloquio

Reputation: 3912

When you say

Form1 f1 = new Form1();

You are creating a whole new object with its own textbox.

If you want the value that is on that textbox of that form, you will need to refer to the same instance of Form1 where the user typed the value.

Upvotes: 3

uowzd01
uowzd01

Reputation: 1000

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();
}

Upvotes: 13

REW
REW

Reputation: 776

Is this pseudo-code, or is this the code you're actually trying to use?

If you're trying to use this code, what you're doing is creating a brand new Form1. Unless the constructor for Form1 puts something into your textbox, it will be empty at this point.

Upvotes: 0

default
default

Reputation: 11635

your textBox is probably private, although that is as it should be. If you need the Text from the textbox you can expose it with a property

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

Upvotes: 6

mjroodt
mjroodt

Reputation: 3313

I think its because you are creating a new instance of form1 so you are actually only getting the textbox text from f1.

Upvotes: 2

Related Questions