New to Telerik UI for WinForms? Start a free 30-day trial
Format the group key of a DateTime value in RadGridView
Updated over 6 months ago
Environment
| Product Version | 2018.3.911 |
| Product | RadGridView for WinForms |
Description
When performing a grouping operation you may need to format or change the group value. For example if you want to group only by date and ignore the time part of a DateTime value. The bellow solution shows how you can use a custom predicate method to change the key values.
Solution
Crete a custom predicate function that is able to parse the descriptors and return the group keys.
C#
private object PerformGrouping(GridViewRowInfo row, int level)
{
GroupDescriptor groupDescriptors = this.radGridView1.GroupDescriptors[level];
object[] key = new object[groupDescriptors.GroupNames.Count];
for (int k = 0; k < groupDescriptors.GroupNames.Count; k++)
{
SortDescriptor descriptor = groupDescriptors.GroupNames[k];
int index = descriptor.PropertyIndex;
if (index < 0)
{
continue;
}
key[k] = this.GetItemKey(row, descriptor);
}
return key;
}
protected virtual object GetItemKey(GridViewRowInfo item, SortDescriptor descriptor)
{
ColorConverter colorConverter = null;
int index = descriptor.PropertyIndex;
object keyValue = item.Cells[index].Value;
if (keyValue == DBNull.Value)
{
keyValue = null;
}
else if (keyValue is Color)
{
if (colorConverter == null)
{
colorConverter = new ColorConverter();
}
Color color = (Color)keyValue;
keyValue = color.IsNamedColor ? color.Name : colorConverter.ConvertToString(color);
}
else if(descriptor.PropertyName == "ContactDate")
{
keyValue = ((DateTime)keyValue).ToShortDateString();
}
return keyValue;
}
Here is how you can assign the above method:
C#
radGridView1.MasterTemplate.GroupPredicate = PerformGrouping;