I have imported data from excel to data grid in wpf application and I am trying to do some math on the data and also combine some columns.Please advise as what would be the best way to handle this.
to solve this I was trying to create a C# class, but I do not know how to map or link my class objects to a column in data grid?
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public int Salary { get; set; }
}
how can I map or link my C# class objects to a column in Data grid?
is it the easy way or I need to put everything into SQL database and write queries, I am good with SQL. Any advise will be highly appreciated. I am trying to figure this out from a real long time.
You can always extend your Person class with extra properties that expose getter only with whatever combinations you want... Something like...
class Person
{
public int Id { get; set; }
// added the = ""; just to prevent nulls
public string Name { get; set; } = "";
public string City { get; set; } = "";
public int Salary { get; set; }
// Now you can show these columns directly in the grid -- just an example
public decimal MonthlySalary { get { return Math.Round(Salary / 12.0, 2 ); } }
public string NameAndCity { get { return Name.Trim() + ", " + City.Trim(); } }
}
I'd start by learning some basics regarding the DataGrid
. This page should be helpful for what you're doing: https://www.wpf-tutorial.com/datagrid-control/custom-columns/
You would define whatever columns you want to show in the DataGrid
between the <DataGrid.Columns>
tags. Each column has a Binding
property which you use to set which property of your class ( Person
) is linked to that column via data bining.
As for doing math, you can create readonly properties for Person
. Inside the readonly properties you could do calculations based on other properties and then return the result. To display the result, you would bind the readonly property to a column on the DataGrid
. Keep in mind that if you the data in your Person
class to be editable at runtime and have the math results update, you'll need to have Person
implement INotifyPropertyChanged
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.