Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I support browsing for a text file and reading it into a TextBox?

You use the Frameworks OpenFileDialog to implement this functionailty.

using System.Text;
using System.IO;

private void button1_Click( object sender, EventArgs e )
{
  OpenFileDialog dlg = new OpenFileDialog();
  dlg.Title = "Open text file" ;
  dlg.InitialDirectory = @"c:\" ;
  dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;

  if ( dlg.ShowDialog() == DialogResult.OK )
  {
    StreamReader sr = File.OpenText( dlg.FileName );
    string s = sr.ReadLine();
    StringBuilder sb = new StringBuilder();
    while ( s != null )
    {
      sb.Append(s);
      s = sr.ReadLine();
    }
    sr.Close();
    textBox1.Text = sb.ToString();
  }
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter