Sunday, March 8, 2009

Locale Manager (3) - Example of Using DirectoryInfo, FolderBrowserDialog and Sharing Data between Different Forms

For part 1 and part 2, please click the following links:
Part 1 - Introduction of Locale Manager
Part 2 - How to: Use Locale Manager

I. Program Structure - using Model to store data

There are two forms in the code: MainForm and WorkSheetForm. MainForm is the one to ask the user to select the base locale directory by file browsing. Then, it displays all the sibling subdirectories of the base directory.
WorkSheetForm will show after the user selects one or more target locales and clicks the Load button. The program will dynamically add columns to the DataGrid depending on how many locales are selected.
This program uses the MVC (Model-View-Controller) pattern to pass data around the UI. Application data is stored in Global.cs, the Model. So, MainForm.cs passes data such as BaseDir, RootDir, and Locales to Global.cs, and WorkSheetForm.cs can go pick it up over there.
II. Using DirectoryInfo, FolderBrowserDialog

FolderBrowserDialog is used instead of a OpenFileDialog so that only folders are shown while user tries to find the base locale directory.

.Net's DirectoryInfo class is very handy and you can retrieve all different info about a directory or a file. The MainForm.cs uses this class to get the base directory and the root locale directory. The fillLocaleList() function finds all the sibling subdirectories and add them to the list box.
private void m_browse_Click(object sender, EventArgs e)
{
 m_baseDirBrowserDlg.SelectedPath = Environment.CurrentDirectory;
 if (m_baseDirBrowserDlg.ShowDialog(this) != DialogResult.OK)
     return;

 Global.BaseDir = new DirectoryInfo(m_baseDirBrowserDlg.SelectedPath);
 Global.RootDir = Global.BaseDir.Parent;

 m_baseLocale.Text = Global.BaseDir.Name;
 fillLocaleList();
}

private void fillLocaleList()
{
 m_allLocales.Items.Clear();
 m_selectedLocale.Items.Clear();

 DirectoryInfo[] subs = Global.RootDir.GetDirectories();

 foreach (DirectoryInfo sub in subs)
 {
     String dirName = sub.Name;
     //exclude base locale dir in the list
     if (dirName != Global.BaseDir.Name)
         m_allLocales.Items.Add(dirName);
 }

 if (m_allLocales.Items.Count > 0)
 {
     m_add.Enabled = true;
     m_addAll.Enabled = true;

     m_allLocales.SelectedIndex = 0;
 }
 else
     MessageBox.Show("No sibling folders were found for the base locale.");
}
The codes will enable buttons only when a user finishes the required steps first. This is very easy to do but will help the user a lot and make the application friendly.

No comments:

Post a Comment