Search code examples
c#radgridviewcell-formatting

Conditional formatting on a radgridview to remove '-' - C#


I have a rad grid view which contains data relating to stock movement. The values in a column named will all be pulled through as negative. I want to add formatting so that the negative is removed from the number.

I think conditional formatting is how I want to do this, I'm unsure of what I want to do after the condition is met.

ConditionalFormattingObject obj = new ConditionalFormattingObject("MyCondition", ConditionTypes.StartsWith, "-", "", false);
obj.CellBackColor = Color.SkyBlue;
obj.CellForeColor = Color.Red;
obj.TextAlignment = ContentAlignment.MiddleRight;
this.rgv_orderLines.Columns["Moved so Far"].ConditionalFormattingObjectList.Add(obj);

The above code will turn the cells blue when the condition is met. I however, don't want this I want the '-' to be removed.

EDIT: The following code gives the desired result, however, without the try catch it crashes on any cells that don't contain a value.

    private void rgv_orderLines_CellFormatting(object sender, CellFormattingEventArgs e)
    {
        if (e.CellElement.ColumnInfo.Name == "Moved so Far")
        {
            try
            {
                string value = e.CellElement.Value.ToString();
                value = value.Replace("-", "");
                e.CellElement.Value = value;
            }
            catch (Exception ex)
            {

            }
        }
    }

Solution

  • ConditionalFormattingObject is used only to style the row, i.e. setting fonts and colours. It does not have functionality for formatting data values.

    Ideally, you should store the data as positive numbers in the first place, as that makes sorting, filtering etc. much easier. But if you do want to just display the value as positive, you should make sure the column is a GridViewDecimalColumn and set the FormatString of the column to something like

    "#.###;#.###;0"

    This means display the value with 3 decimal places, for both positive and negative numbers, and as 0 for 0.

    If it is a string column, your code wold work, just check if the Value is null before formatting it:

    private void rgv_orderLines_CellFormatting(object sender, CellFormattingEventArgs e)
    {
        if (e.CellElement.ColumnInfo.Name == "Moved so Far")
        {
            if(e.CellElement.Value != null)
            {
                string value = e.CellElement.Value.ToString();
                value = value.Replace("-", "");
                e.CellElement.Value = value;
            }
        }
    }