Home > other >  How can I bind number of days left into a DataGrid?
How can I bind number of days left into a DataGrid?

Time:02-23

I'm trying to resolve a problem, where I need to count number of days until a due.

I'm using LinqToSql, WPF.

In my Sql, I have some dates (one for each person,(type Date)), that represents the last possible day for something to be paid, for example.

enter image description here

My question is, how can I count number of days left for it to be payed, for each person, and then, how can I bind them to my DataGrid?

enter image description here

This is my XAML code

<DataGrid  Margin="58,0,0,160" Name="dgData" HorizontalAlignment="Left" Width="612" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Ime}"></DataGridTextColumn>
            <DataGridTextColumn Header="Lastname" Binding="{Binding Prezime}"></DataGridTextColumn>
            <DataGridTextColumn Header="Days left"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

This is how I fill my DataGrid

ProbaDataContext proba = new ProbaDataContext();
    
    DateTime today = DateTime.Now;
    int nmbDays;

    public MainWindow()
    {
        InitializeComponent();

        dgData.ItemsSource = proba.Radniks.ToList();

        var sourceList = dgData.ItemsSource as List<Radnik>;
        //this is the only thing i menaged to do, count all the days left
        foreach(var item in sourceList)
        {
            DateTime datum = (DateTime)item.Datum;

            nmbDays = (datum.Date - today.Date).Days;
            txtDatum.Text = nmbDays.ToString();
        }           
    }

CodePudding user response:

You can use the IValueConverter and binding on database field Datum.

https://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/

CodePudding user response:

You can use an auxiliar child class to fill the datagrid and do the calcs there:

    private class AuxRadnik:Radnik
    {
        public int DaysLeft
        {
            get
            {
                return (this.Datum - DateTime.Now).Days;
            }
        }
    }

Then change your code to populate de ItemSource correctly:

public MainWindow()
{
    InitializeComponent();

    dgData.ItemsSource = proba.Radniks.Select(r=> new AuxRadnik 
          {Ime = r.Ime, 
           Prezime = r.Prezime, 
           Datum = r.Datum 
          }).ToList();         
}

And lastly bind on the XAML part

<DataGrid  Margin="58,0,0,160" Name="dgData" HorizontalAlignment="Left" Width="612" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Ime}"></DataGridTextColumn>
        <DataGridTextColumn Header="Lastname" Binding="{Binding Prezime}"></DataGridTextColumn>
        <DataGridTextColumn Header="Days left" Binding="{Binding DaysLeft}"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>
  • Related