Reputation: 1
I'm very new at this and I am attempting to take text from a .txt file and input it into a text box.
I have tried to read text from a file that has been located on my computer
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (File.ReadAllText("F:\\Example"));
}
I need textBox1 to display the text that is in "F:\Example"
Upvotes: 0
Views: 158
Reputation: 769
if you use Form_Load then you should read the file asynchronously because any file loading time will freeze your form from being displayed. For instance, if your file takes 5 seconds to load then the form will not be visible for 5 seconds.
Here's an example that uses Task.Run to load the data asynchronously then display it. If first shows the form with message "Loading data...", then the text box is updated once the data has been loaded.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Text = "Loading data...";
LoadData();
}
private async void LoadData()
{
string text = null;
await Task.Run(() =>
{
text = File.ReadAllText("z:\\very_large_file.txt");
});
this.textBox1.Text = text;
}
}
There are of course many other ways to load a file asynchronously (e.g. using streams) but I think this sample code is easier to understand.
Hope this helps :)
Upvotes: 0
Reputation: 2079
This example adds a handler to the form's OnLoad event:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Text = File.ReadAllText(@"F:\Example");
}
}
}
Upvotes: 2
Reputation: 475
As @John said, if you want to display a text after form load you can use Form.Load event directly or you can override it like so:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
textBox1.Text = File.ReadAllText("F:\\Example");
}
You can also load text by button click.
Upvotes: 0