Formatting the value of a grid cell is one of the most common tasks when working with data grids. Most spreadsheet applications like 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 DataGrid for WinForms, 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 data grid as dollar values with two digits behind the decimal point:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a pseudo-random number generator
Random rand = new Random();
// Add two columns
HierarchyItem column1 = vDataGridView1.ColumnsHierarchy.Items.Add("Unformatted Column");
HierarchyItem column2 = vDataGridView1.ColumnsHierarchy.Items.Add("Formatted Column");
// Add 10 rows
for (int iRow = 0; iRow < 10; iRow++)
{
HierarchyItem row = vDataGridView1.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
vDataGridView1.CellsArea.SetCellValue(row, column1, value);
vDataGridView1.CellsArea.SetCellValue(row, column2, value);
// set the cell alignment to MiddleRight
vDataGridView1.CellsArea.SetCellTextAlignment(row, column1, ContentAlignment.MiddleRight); vDataGridView1.CellsArea.SetCellTextAlignment(row, column2, ContentAlignment.MiddleRight);
}
// Create a named format expression
vDataGridView1.CellsArea.CellFormatting.SetFormatter("format1", null, "${0:##.00}");
// Assign the format expression to all cells under the second grid column
vDataGridView1.CellsArea.CellFormatting.SetCellFormatting(column2, "format1");
// Refresh the grid's content
vDataGridView1.Refresh();
}
}
In addition, VIBlend DataGridView allows you to use custom format providers to achive maximum flexibility.