djuzla123
djuzla123

Reputation: 1

c# getting value from other form

Situation i have: textbox(to input your name) on form1. From that form1 on button click i go to form2. From form2 button click to form3. On form3 on button click i need to writte me in empty textbox value from textbox on form1 that user wrote down. example: on form1 in textbox1 i write my name "Djuzla". When i go to form3 and click button to see what name i wrote in form1 it should show in empty textbox3 form3 "Djuzla".

I'm stuck with this few hours now, and it stupid problem but i have no idea what to do next.. tried all from zillion theards on net :p

Upvotes: 0

Views: 330

Answers (5)

Mark H
Mark H

Reputation: 13897

The solutions that pass a value around can get quite sloppy because there's no guarantee that the value inside the textbox won't change after you've already passed it somewhere. Instead, it's more sensible to pass a function around which resolves the value from the TextBox when called, which will result in always getting the lastest value.

void button1_Click() {
    form2 = new Form2(() => textBoxName.Text);
}

class Form2 : Form {
    ...
    public Form2(Func<String> nameResolver) {
        form3 = new Form3(nameResolver);
    }

    void button1_Click(...) {
       form3.Show()
    }
}

class Form3 : Form {
    Func<String> nameResolver;

    public Form3(Func<string> nameResolver) {
        this.nameResolver = nameResolver;
    }

    void button1_Click(...) {
        this.textBoxName = nameResolver.Invoke();
    }
}

If you end up requiring more than one or two components shared between the various forms, it might be better to simply pass the forms themselves to child forms. Eg.

void button1_Click(...) {
    form2 = new Form2(this);
}

class Form2 : Form {
    Form1 parent;
    public Form2(Form1 parent) {
        this.parent = parent;
    }

    void button1_Click(...) {
        form3 = new Form3(parent);
    }
}

Upvotes: 0

DRapp
DRapp

Reputation: 48139

I've answered similarly... Since you are going from Form 1 to 2 to 3, you could basically take the same approach in this solution to cascade the value out and back as needed, not just one way...

My Other Solution to similar question...

Upvotes: 0

mrcomplicated
mrcomplicated

Reputation: 231

You could modify the constructor of the form to take one more argument to hold the value of the textBox.

Upvotes: 2

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

You may access the PreviousPage property from the page, or set a session variable (or a cookie) and then retrieve it on page load etc. but the most straightforward solution is to use the PreviousPage property on the page to access the data from previous page.

Upvotes: 0

oivindth
oivindth

Reputation: 870

Store the value in a property. If you are developing for asp.net, use session or ViewState. Did I understand your question?

Upvotes: 0

Related Questions