1

I have a form, called Form1 and a class, called Class1. On the form i have a textbox (textBox1) and a button (button1).

I want nothing else, just to set textBox1.Text as a string in Class1. I made a property in Form1.cs called TextValue but if i want to use it in Class1 as "string tv=Form1.TextValue;" an error occurs, that "An object reference is required for the non-static field, method, or property 'Form1.TextValue'". I think everything has set as non-static, but i am confused now.

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public string TextValue
        {
             get
            {
                return textBox1.Text;
            }
            set
            {
                textBox1.Text = value;
            }
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}

namespace WindowsFormsApp2
{
    public class Class1
    {
        string tv=Form1.TextValue;
    }
}

Can you kindly help me how i should modify my code to be able to get the string "tv" with the textBox1.Text?

Thank you in advance.

Chrissy
  • 11
  • 1
  • May be helpful: https://stackoverflow.com/questions/4587952/passing-data-between-forms | https://stackoverflow.com/questions/7273862/c-sharp-how-to-make-two-forms-reference-each-other – Jaskier Feb 13 '19 at 20:24
  • 2
    In your `Class1` you would have to first instantiate a new instance of `Form1` (or have an instance passed into the constructor, or some other means of getting an instance) in order to access an instance property like `TextValue`. Currently the relationship between these two classes is not clear (which one would instantiate the other). – Rufus L Feb 13 '19 at 20:28

1 Answers1

0

In the code you posted, TextValue is not a static, true. In Class1 you are attempting to declare a non-static member called tv. The problem is, you are initializing tv with the expression Form1.TextValue. In the context of that expression, the use of Form1 is a type reference, so the compiler is "thinking" TextValue is static, which it is not.

Instead, you will need to instantiate Class1 somewhere and, perhaps, pass in the textbox's value.

Something like this

...
private void button1_Click(object sender, EventArgs e)
{
    var value = new Class1(textbox1.Text);
}

...
public class Class1
{
    public Class1(string textboxText) => tv = textboxText;

    string tv;
}
Kit
  • 20,354
  • 4
  • 60
  • 103
  • Thank you, i don't get any error but it seems it's still not working. I mean if i write a text to the textBox1, the variable "tv" in Class1 doesn't get the text as it's value. – Chrissy Feb 14 '19 at 08:54