Formatting the value of a grid cell is one of the most common tasks when working with data grids. Most spreadsheet applications, like Microsoft Excel, provide a built-in list with the most common cell formats. These include format expressions for numbers, currencies, dates, hours, and more. In addition, the user can easily create a custom cell format expression.
VIBlend SuperGridView, allows you to format the content a grid cell through a simple expression which follows the .NET string formatting rules. The value of a grid cell can be any object type, and it is up to you to specify how this value will be converted to text. Unless you associate the cell, or its column, with a format expression, the grid will try to get the text representation of the cell’s value by calling the ToString() method.
The code below formats all cells in the second column of the datagrid as dollar values with two digits behind the decimal point:
private void Form1_Load(object sender, EventArgs e)
{
// Create a pseudo-random number generator
Random rand = new Random();
// Add two columns
HierarchyItem column1 = superGridView1.ColumnsHierarchy.Items.Add("Unformatted Column");
HierarchyItem column2 = superGridView1.ColumnsHierarchy.Items.Add("Formatted Column");
// Add 10 rows
for (int iRow = 0; iRow < 10; iRow++)
{
HierarchyItem row = superGridView1.RowsHierarchy.Items.Add(string.Format("Row {0}", iRow + 1));
// Generate a random number
double value = rand.NextDouble() * 100.0f;
// Set cell value at (currentRow;column1) and (currentRow;column2) to the random number
superGridView1.DataFieldArea.SetCellValue(row, column1, value);
superGridView1.DataFieldArea.SetCellValue(row, column2, value);
// set the cell alignment to MiddleRight
superGridView1.DataFieldArea.SetCellTextAlignment(row, column1, ContentAlignment.MiddleRight);superGridView1.DataFieldArea.SetCellTextAlignment(row, column2, ContentAlignment.MiddleRight);
}
// Create a named format expression
superGridView1.DataFieldArea.CellFormatting.SetFormatter("format1", null, "${0:##.00}");
// Assign the format expression to all cells under the second grid column
superGridView1.DataFieldArea.CellFormatting.SetItemFormatting(column2, "format1");
// Refresh the grid's content
superGridView1.Refresh();
}
In addition, SuperGridView allows you to use custom format providers to achive maximum flexibility.