WinForms FAQ - Common Dialogs

Find answers for the most frequently asked questions
Expand All Collapse All

Below is a technique that uses FolderNameEditor and FolderBrowser classes to implement a solution. You can also use iterop to get a solution.

Both the FolderNameEditor and FolderBrowser classes used in this solution are described in the Docs as ‘This type supports the .NET Framework infrastructure and is not intended to be used directly from your code.’

	// add a reference to System.Design.DLL

	using System.Windows.Forms.Design;
	.............

	public class DirBrowser : FolderNameEditor
	{
		FolderBrowser fb = new FolderBrowser();

		public string Description
		{
			set { _description = value; }
			get { return _description; }
		}

		public string ReturnPath
		{
			get { return _returnPath; }
		}

		public DirBrowser() { }

		public DialogResult ShowDialog()
		{
			fb.Description = _description;
			fb.StartLocation = FolderBrowserFolder.MyComputer;

			DialogResult r = fb.ShowDialog();
			if (r == DialogResult.OK)
				_returnPath = fb.DirectoryPath;
			else
				_returnPath = String.Empty;

			return r;
		}

		private string _description = 'Choose Directory';
		private string _returnPath = String.Empty;
	}

(Posted by Ryan Farley on the microsoft.public.dotnet.language.csharp newsgroup)

Permalink
	using System.Text;
	using System.IO;
	....
	private void button1_Click(object sender, System.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();
		} 
	}
Permalink

It is straight-forward. Create an instance of the class and call its ShowDialog method.

	ColorDialog colorDialog1 = new ColorDialog(); 
	//fontDialog1.ShowColor = true; 
	if(colorDialog1.ShowDialog() != DialogResult.Cancel ) 
	{ 
		textBox1.ForeColor = colorDialog1.Color; 
	} 
	textBox1.Text = 'this is a test'; 
Permalink

It is straight-forward. Create an instance of the class and call its ShowDialog method.


     FontDialog fontDialog1 = new FontDialog(); 
      fontDialog1.ShowColor = true; 
      if(fontDialog1.ShowDialog() != DialogResult.Cancel ) 
      { 
           textBox1.Font = fontDialog1.Font ; 
           textBox1.ForeColor = fontDialog1.Color; 
      } 
  
     textBox1.Text = 'this is a test'; 
Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.