Search code examples
c#data-bindingdatagridview

Data Binding to DataGridView


Im using a List<Patient> object as the data source to a data grid view. I need to use concatenation of two string properties in the Patient class as the value of a single text box column. I know this can be done by using the OnRowDataBound event in the webforms GridView. How to handle this situation in win forms? I cant see OnRowDataBound event in the win forms Data grid view.

For clarification my Patient class is,

public class Patient
{
    public string Initials { get; set; }
    public string LastName { get; set; }
}

I need to bind the combination of these two properties to a single column called 'Name' in the grid view. And also there are some other properties in the Patient class which are directly mapped to the data grid view columns using the DataPropertyName of columns. So it is tedious to fill all the columns programmatically.


Solution

  • One easy solution is adding a new property that computes the value to your (view) model and binding to this property.

    public class Patient
    {
        public string Initials { get; set; }
        public string LastName { get; set; }
    
        public string InitialsAndLastName
        {
            get { return this.Initials + " " + this.LastName; }
        }
    }