We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to implement a converter when table rows/columns are generated dynamically

Hello,

I'm using the SfDataGrid and need to use a converter to set an image (red or green circle) based on a cell value ( true or false ).  When I define the grid in XAML
and specify the column type, then everything is fine. I can use GridImageColumn and a converter to do the work.

However I have another situation where the grid is bound to a DataTable which is created in code, not XAML.  So my XAML looks like this:

<syncfusion:SFDataGrid ItemSource="dtPermissions" />

In my viewmodel I create all the rows and columns dynamically ( the rows and column names are variable ),  so it could be like

Column1               Team 1        Team 2        Team 3
========           ======       ======       ======
Project 1                   Y                 N                 N
Project 2                   Y                 N                 Y
Project 3                   Y                 Y                 N

So the Y's need to be green circle images, and the N's need to be red.   But since the columns and rows are unknown until runtime, it's not possible to define
them in XAML. 

Any suggestions on how this can be done?

thanks



1 Reply

JN Jayaleshwari N Syncfusion Team February 20, 2019 11:34 AM UTC

Hi Milan, 
 
Thanks for contacting Syncfusion Support. 
 
We have checked the reported query “How to implement a converter when table rows/columns are generated dynamically” from our side. you can add the converter to GridImageColumn when you generate rows and columns dynamically.  
 
Code snippet C#: Converter to convert bool value to image. 
 
public class BoolToImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        var isAvailable = bool.Parse(value.ToString()); 
        string imageName = isAvailable ? "Green.png": "Red.png"; 
        return new BitmapImage(new Uri(string.Format(@"..\..\Images\{0}", imageName), UriKind.Relative)); 
    } 
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        throw new NotImplementedException(); 
    } 
} 
 
Code snippet C#: add converter to GridImageColumn  
 
sfdatagrid.Columns.Add(new GridImageColumn() { MappingName = "IsAvailable", ValueBinding = new Binding() { Path = new PropertyPath("IsAvailable"), Converter = new BoolToImageConverter() } }); 
 
Please let us know if you would require further assistance. 
 
Regards, 
Jayaleshwari N. 


Loader.
Live Chat Icon For mobile
Up arrow icon