MrPatterns
MrPatterns

Reputation: 4434

How do I take the text from a textbox and make it into a usable file path in C#?

Here's my working code:

string outputpath = @"C:\today\abc.txt";
var outputdata = query.ToList();
File.AppendAllLines(outputpath, outputdata);

Now instead of defining "outputpath" in the code, I want to set it equal to the contents of a textbox.

string outputpath = textBox1.Text;

This doesn't compile. What am I doing wrong?

EDIT: The error I get is "Error 1, A field initializer cannot reference the non-static field, method, or property 'WindowsFormsApplication1.Form1.textBox1'.

Upvotes: 2

Views: 106

Answers (1)

Michael
Michael

Reputation: 1833

Looks like you are trying to initalize a field based on the value of a non-static object. You can't do that, since the object doesn't exist during initialization.

This is no good:

public class Form
{
    TextBox textBox1;
    string outputPath = textbox1.Text;
}

This should work, although the value will probably be an empty string:

public class Form
{
    TextBox textBox1;
    string outputPath;

    public Form()
    {
        outputPath = textBox1.Text;
    }
}

But what you probably want is to hook a button's OnClick event, or something similar, to assign the textBox1.Text value to outputpath.

Upvotes: 1

Related Questions