Search code examples
datagridviewseparation-of-concernsbindinglist

How to customize a cell of DataGridView based on the BindingList<T> to which the grid is bound


I am using a DataGridView in a Win Forms app that is bound to a BindingList and I would like to improve on the "separation" of business-logic and presentation.

In my Form_Load event, I call a routine to build a BindingList and then I set the .DataSource of the DGV to this BindingList:

private void initializeFileList(string rootFolder) // populate grid with .xml filenames to be processed
    {
        String root = rootFolder;
            var result = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories)
                    .Select(name => new InputFileInfo(name))
                    .ToList();
            _filesToParse =  new BindingList<InputFileInfo>(result.ToList());
            dataGridView1.DataSource = _filesToParse;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView1.Columns["Rows"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridView1.Columns["Message"].DefaultCellStyle.ForeColor = Color.Red;

It's the last 2 statements that bother me; as you can see, I want minor cosmetic changes to the columns created from the "Rows" and "Message" properties. It feels smelly that I should be hardcoding the properties of my custom object in these last 2 lines.

Would there be a more elegant way of customizing these 2 columns of the DGV - with the goal of fully exploiting the binding provided by: dataGridView1.DataSource = _filesToParse; In other words, still customize the columns but do so from something in the "business" object rather than the current technique.

Here is my InputFileInfo class (from another project in same solution):

namespace CBMI.Common
{
public class InputFileInfo : INotifyPropertyChanged
{
    private bool processThisFile;
    public bool Process
    {
        get { return processThisFile; }
        set
        {
            Utilities.Set(this, "Process", ref processThisFile, value, PropertyChanged);
        }
    }
    public string FileName { get; set; }
    private long rowsReturned;
    public long Rows
    {
        get { return rowsReturned; }
        set
        {
            Utilities.Set(this, "Rows", ref rowsReturned, value, PropertyChanged);
        }
    }
    private string message;
    public string Message
    {
        get { return message; }
        set
        {
            Utilities.Set(this, "Message", ref message, value, PropertyChanged);
        }
    }
    // constructor
    public InputFileInfo(string fName)
    {
        Process = true;
        FileName = fName;
        Rows = 0;
        Message = String.Empty;
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
public static class Utilities
{
public static void Set<T>(object owner, string propName,
    ref T oldValue, T newValue, PropertyChangedEventHandler eventHandler)
{
    // make sure the property name really exists
    if (owner.GetType().GetProperty(propName) == null)
    {
    throw new ArgumentException("No property named '" + propName + "' on " + owner.GetType().FullName);
    }
    // we only raise an event if the value has changed
    if (!Equals(oldValue, newValue))
    {
        oldValue = newValue;
        if (eventHandler != null)
        {
        eventHandler(owner, new PropertyChangedEventArgs(propName));
        }
    }
}

}

}


Solution

  • I don't really see an alternative solution that is going to be easier than what you have provided. You shouldn't mix some sort of CellStyle in with your data bound object as that is not good practice.

    The only thing I would suggest is disabling AutoGenerateColumns and define your own styling:

    private static void AdditionalInitialization(DataGridView dgv, object dataSource) {
    
     dgv.AutoGenerateColumns = false;
     dgv.DataSource = dataSource; // Needs to occur after the auto generate columns is set to off
     DataGridViewTextColumn msgCol = new DataGridViewTextColumn();
     msgCol.HeaderText = "Message";
     msgCol.DataPropertyName = "Message";
     msgCol.DefaultCellStyle.ForeColor = Color.Red;
     dgv.Columns.Add(msgCol);
    }
    

    This method could be placed in any of your classes since it is static, i.e. your InputFileInfo.cs

    Then when your form loads do this:

    private void initializeFileList(string rootFolder) // populate grid with .xml filenames to be processed
    {
        String root = rootFolder;
            var result = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories)
                    .Select(name => new InputFileInfo(name))
                    .ToList();
            _filesToParse =  new BindingList<InputFileInfo>(result.ToList());
            InputFileInfo.AdditionalInitialization(datagridview1,_filesToParse);
    

    }