b13rg
b13rg

Reputation: 490

Why does this code generate a CS1525 ("invalid expression") compiler error?

I'm trying to make a program that, when a button is pressed, takes the words typed in the text box and adds it to a text file. This is what I have so far:

private void textBox1_TextChanged(object sender, EventArgs e)
{
   File.WriteAllText(path, string());
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    File.WriteAllText(path, string());
}

The String keeps coming up with error code CS1525 ("invalid expression"). What am I doing wrong?

Upvotes: 0

Views: 166

Answers (2)

sa_ddam213
sa_ddam213

Reputation: 43596

You will want to use the string from the TextBox.Text property

for example

 File.WriteAllText(path, textBox1.Text);

or

 File.WriteAllText(path, (sender as TextBox).Text);

And it sounds like you want to create a Button and assign a Click event and use that to save the Text from the TextBox to the file, and for that AppendAllText may be a better option.

private void button1_Click(object sender, EventArgs e)
{
    File.AppendAllText(path, textBox1.Text);
}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

Try this:-

using (StreamWriter sw1 = new StreamWriter("abc.txt"))
{
    sw1.WriteLine(textBox1.Text);
}

or

private void textBox1_TextChanged(object sender, EventArgs e)
{
   File.WriteAllText(path,textBox1.Text);
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    File.WriteAllText(path,textBox2.Text);
}

Upvotes: 0

Related Questions