Sunday, March 8, 2009

Locale Manager (4) - Dynamically Add Columns/Rows to a DataGrid

For other parts, please click the following links:
Part 1 - Introduction of Locale Manager
Part 2 - How to: Use Locale Manager
Part 3 - Example of Using DirectoryInfo and FolderBrowserDialog

III. Dynamically Add Columns to a DataGrid
If the datagrid you want to display always has the same number of columns and the headers remain the same, you can just configure the datagrid through property settings. However, sometimes the number of columns and headings depends on user's input, we need to dynamically add columns to the datagrid.

The following codes show how colomns are added to the Datagrid on Worksheet form based on which target locales user selects. Column index comes from enumeration of columns:
public enum Columns
{
No = 0, File, Name, Base
};

private void WorkSheetForm_Load(object sender, EventArgs e)
{
FileInfo[] files = Global.BaseDir.GetFiles("*"+ Global.Extension);
...
...
//determine number of columns for the datagrid
m_grid.ColumnCount = Global.Locales.Length + (int)Columns.Base + 1;
_numOfCols = m_grid.ColumnCount;

m_grid.Columns[(int)Columns.No].Name = "no.";
m_grid.Columns[(int)Columns.No].ValueType = typeof(int);

m_grid.Columns[(int)Columns.File].Name = "file";
m_grid.Columns[(int)Columns.Name].Name = "name";
m_grid.Columns[(int)Columns.Base].Name = Global.BaseDir.Name;

int i = (int)Columns.Base + 1;
foreach (string locale in Global.Locales)
m_grid.Columns[i++].Name = locale;
...
}

When the column "no." is added, I set its ValueType to int, otherwise it is going to be string by default. This matters when user clicks the header to do a sort. If the value type is string, the sorted result will be "1, 11, 2, 21, ..." instead of "1, 2, 3, ...".

m_grid.Columns[(int)Columns.No].Name = "no.";
m_grid.Columns[(int)Columns.No].ValueType = typeof(int);

IV. Dyanmically Add Rows to the Datagrid
The function AddRowToGrid() shows how to add a new row to the datagrid. The function AddToRow() shows how to fill out cells or access cell values in an existing row.

private void AddRowToGrid(string file, int i, string name, string value)
{
string[] row;
row = new string[_numOfCols];
row[(int)Columns.No] = i.ToString();
row[(int)Columns.File] = file;
row[(int)Columns.Name] = name.Trim();
row[(int)Columns.Base] = value.Trim();

m_grid.Rows.Add(row);
}

private void AddToRow(int i, int localeIndex, string value)
{
if (null!= value && i>=0)
m_grid.Rows[i].Cells[getColumnNo(localeIndex)].Value = value;
}

private int getColumnNo(int localeIndex)
{
return (int)Columns.Base + localeIndex + 1;
}

No comments:

Post a Comment