how to add unbound field and calculate number of days between 2 dates

Hello,

  1. Is there a way in Blazor grid where I can insert an unbound field for holding the calculated value between 2 dates?
  2. If the answer above is Yes, could I hide the calculated field during adding new record?

My code is:

   <SfGrid DataSource="@ListImportantDate" ID="Grid" AllowTextWrap=true AllowExcelExport=true @ref="DefaultGrid" TValue="ImportantDate"

                Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update", "ExcelExport" })"

                AllowFiltering="true" AllowPaging="true" AllowSorting=true>

            <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true" Mode="EditMode.Dialog" ShowDeleteConfirmDialog="true"></GridEditSettings>

            <GridEvents OnActionBegin="ActionBeginHandler" OnToolbarClick="ToolbarClickHandler" TValue="ImportantDate"></GridEvents>

            <GridPageSettings PageSize="10"></GridPageSettings>

            <GridTemplates>

                <EmptyRecordTemplate>

                    <span>Custom no record message</span>

                </EmptyRecordTemplate>

            </GridTemplates>

            <GridColumns>

                <GridColumn Field="@nameof(ImportantDate.ID)" Width="30" IsPrimaryKey=true IsIdentity=true Visible=true></GridColumn>

                <GridColumn Field="@nameof(ImportantDate.DateFrom)" HeaderText="Date From" Width="40" HeaderTextAlign="TextAlign.Center" EditType="EditType.DatePickerEdit" Format="d" TextAlign="TextAlign.Right"></GridColumn>


                <GridColumn Field="@nameof(ImportantDate.DateTo)" HeaderText="Date To" Width="40" HeaderTextAlign="TextAlign.Center" EditType="EditType.DatePickerEdit" Format="d" TextAlign="TextAlign.Right"></GridColumn>

                <GridColumn Field="NumDays" Width="50" ></GridColumn>


                <GridColumn Field="@nameof(ImportantDate.Remarks)" HeaderText="Remarks" EditType="EditType.DefaultEdit" Width="250"></GridColumn>

                <GridColumn Field="@nameof(ImportantDate.DateInsert)" Visible=false Width="50" DefaultValue=@dt Format="d" TextAlign="TextAlign.Right"></GridColumn>

                <GridColumn Field="@nameof(ImportantDate.DateUpdate)" Visible=false Width="50" DefaultValue=@dt Format="d" TextAlign="TextAlign.Right"></GridColumn>

            </GridColumns>

            <GridSortSettings>

                <GridSortColumns>

                    <GridSortColumn Field="ID" Direction="SortDirection.Descending"></GridSortColumn>

                </GridSortColumns>

            </GridSortSettings>

        </SfGrid>


Regards


Attachment: Calculte_2_dates_b358f891.rar

11 Replies

RS Renjith Singh Rajendran Syncfusion Team June 14, 2022 02:35 PM UTC

Hi Sao,


Greetings from Syncfusion support.


Query 1 : where I can insert an unbound field for holding the calculated value between 2 dates?

You can use the Template Column feature of grid to achieve this requirement. You can fetch the corresponding row data values using context inside Template column. Please refer the codes below,


 

        <GridColumn Field=@nameof(Order.DateTo) HeaderText=" Order Date" EditType="EditType.DatePickerEdit" Format="d" TextAlign="TextAlign.Right" Width="130" Type="ColumnType.Date"></GridColumn>

        <GridColumn Field=@nameof(Order.DateFrom) HeaderText=" Order Date" EditType="EditType.DatePickerEdit" Format="d" TextAlign="TextAlign.Right" Width="130" Type="ColumnType.Date"></GridColumn>

       

        <GridColumn HeaderText="NumDays" Width="50" >

            <Template>

            @{

                var rowvalue = context as Order;

            }

            <div>Here you can access the @rowvalue.DateTo and @rowvalue.DateFrom values, and do your custom action</div>

            </Template>

        </GridColumn>

 


Query 2 : could I hide the calculated field during adding new record?

Based on this scenario to customize the grid add form dialog, we suggest you to use the Dialog Template feature of grid. With this feature you can customize the contents you need to display in the add/edit dialog of grid. Please refer the below references for more details.

https://blazor.syncfusion.com/documentation/datagrid/template-editing#dialog-template


Please get back to us if you need further assistance.


Regards,

Renjith R



OD oddssatisfy February 16, 2023 04:25 PM UTC

@Sao

Hello,

I want to calculate the number of days between two date fields. but this give me the less number of days between the two dates.

For example, the dates are 17-05-2021 to 18-05-2021, I am using the script below, the script is returning the value of '1', whereas it should be '2'. How can I get the correct value?

function setNumberOfDays() {

var start = current.u_start_date;

var end = current.u_end_date;

var d = gs.dateDiff(date1, date2, true);

current.u_total_number_of_days = d;
}

Thanks in advance.



SP Sarveswaran Palani Syncfusion Team February 21, 2023 04:30 AM UTC

Hi Sao & team,

Greetings from Syncfusion support.

From your query, we suspect that you’re facing issue in calculating the number of days using the JavaScript. We prepared code sample based on your requirement. Kindly refer the below code sample.


const date1 = new Date('2022-05-17');

const date2 = new Date('2022-05-18');

 

const timeDiff = date2.getTime() - date1.getTime();

 

const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

 

console.log(diffDays); // Output: 1


In the above code sample, getTime() method is used to calculate the time difference between the two dates in milliseconds, which is then divided by the number of milliseconds in a day (i.e., 1000 * 3600 * 24) to get the number of days between the two dates. The Math.ceil() function is used to round up the result to the nearest integer.

If you’re still facing an issue, kindly share the runnable sample to us. It’ll be useful for us to further evaluate your query.

Regards,
Sarvesh



SA Sao February 21, 2023 06:14 AM UTC

Hi, Sarvesh,

I am not using JavaScript, I used C# and Razor.


Thank you for the post.


Sao



SP Sarveswaran Palani Syncfusion Team February 24, 2023 11:11 AM UTC

Hi Sao,

Sorry for the inconvenience caused.

Based on your requirement, we prepared sample to calculate number of days between two date fields and it work’s properly at our end. Kindly refer the attached sample for your reference.

If you have any further queries, please don’t hesitate to get back to us.

Regards,
Sarvesh


Attachment: SfGridColumn_99fb694d.zip


KH koilte hight March 7, 2023 11:35 AM UTC

Hi.

Please Help.

I need to save result of count between 2 Date in DataBase when Add New Record on Holyday Table.

so I tried that but I could not,


 <GridColumn Field=@nameof(HolidayDto.HolidayDays) HeaderText="Holiday Days" Width="120">

                <Template >

                    @{

                        var value = (context as HolidayDto);

                        var HolidayDays = value.DateEnd - value.DateStart;

                        <div>@HolidayDays.Days</div>

                    }

                </Template>

How I can bind result days to Field=@nameof(HolidayDto.HolidayDays).

--------------------------------------------------------------------------------------------------------

MY CODE:

@page "/emps/holiday/{Id:int}"

@inject IEmpRepository _empRepository

@inject IHolidayRepository _holidayRepository

@using Syncfusion.Blazor.Data;

@using Syncfusion.Blazor.Cards;

@using Syncfusion.Blazor.DropDowns;



<h3 class="card-title text-primary mb-3 ml-3">Add Holiday</h3>

 @if (IsLoading)

{

             <div class="text-center">

               <img src="/images/loading.gif">

    </div>

}

else

{

    <div class="row border p-2 mb-2">

        <div class="col-4">

            <div class="card-body">

                <h4>@Emp.FileNumber</h4>

                <h4>@Emp.FullName</h4>

            </div>

        </div>

        <div class="col-1">

            <img src="@Emp.ImageUrl" class="w-100">

        </div>

    </div>


    <SfGrid @ref="holidayGrid" DataSource="@Holidays" AllowPaging="true" Toolbar="@(new List<string>{"Add","Edit","Update","Delete","Cancel",})">

        <GridEditSettings AllowAdding="true" Mode="EditMode.Dialog" AllowEditing="true" ShowDeleteConfirmDialog="true" AllowDeleting="true"></GridEditSettings>

        <GridEvents OnActionBegin="ActionHandler" TValue="HolidayDto"></GridEvents>

        <GridPageSettings PageSize="5" PageCount="5" PageSizes="true"></GridPageSettings>

        <GridColumns>

            <GridColumn IsPrimaryKey="true" Field=@nameof(HolidayDto.Id) AllowAdding="false" Width="40"></GridColumn>

            <GridColumn Field=@nameof(EjazaDto.HolidayType) HeaderText="Holiday Type" Width="120">

                <EditTemplate>

                    <Syncfusion.Blazor.DropDowns.SfDropDownList DataSource="HolidayType" TItem="string" TValue="string"

                                                            @bind-Value="((context as HolidayDto).HolidayType)">

                    </Syncfusion.Blazor.DropDowns.SfDropDownList>

                </EditTemplate>

            </GridColumn>

            <GridColumn Field=@nameof(HolidayDto.DateStart) HeaderText="Date Start" Format="d" Width="120"></GridColumn>

            <GridColumn Field=@nameof(HolidayDto.DateEnd) HeaderText="Date End" Format="d" Width="120"></GridColumn>

            <GridColumn Field=@nameof(HolidayDto.HolidayDays) HeaderText="Holiday Days" Width="120">

                <Template >

                    @{

                        var value = (context as HolidayDto);

                        var HolidayDays = value.DateEnd - value.DateStart;

                        <div>@HolidayDays.Days</div>

                    }

                </Template>

            </GridColumn>

        </GridColumns>

    </SfGrid>

}


@code {

    [Parameter]

    public int Id { get; set; }

    private EmpDto Emp { get; set; } = new();

    private IEnumerable<HolidayDto> Holidays { get; set; } = new List<HolidayDto>();

    public bool IsLoading { get; set; }

    public SfGrid<HolidayDto> holidayGrid;


    IEnumerable<String> HolidayType = new List<String>()

    {

        "Medical",

        "Academic",

        "Tourism",

         "Athlete",

        "Other"

    };


    protected override async Task OnAfterRenderAsync(bool firstRender)

    {

        if (firstRender)

        {

            IsLoading = true;

            StateHasChanged();

            Emp = await _empRepository.Get(Id);

            Holidays = await _holidayRepository.GetAll(Id);

            IsLoading = false;

            StateHasChanged();

        }

    }


    public async void ActionHandler(ActionEventArgs<HolidayDto> args)

    {


        if (args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Save))

        {

            args.Data.EmpId = Id;

            if (args.Action == "Add")

            {

                await _holidayRepository.Create(args.Data);

                Holidays = await _holidayRepository.GetAll(Id);

                ejazaGrid.Refresh();

            }

            if (args.Action == "Edit")

            {

                await _holidayRepository.Update(args.Data);

                holidayGrid.Refresh();

            }

        }

        if (args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.Delete))

        {

            await _holidayRepository.Delete(args.Data.Id);

            holidayGrid.Refresh();

        }

    }

}





SP Sarveswaran Palani Syncfusion Team March 11, 2023 06:19 AM UTC

Hi Koilte,

Sorry for the inconvenience caused.

From your query, we suspect that you’re facing issue calculating days between two days, when adding the new data to the Grid table by programmatic methods. We prepared a sample based on your requirement. Kindly refer the attached sample for your reference. And also, please refer the below methods to perform CRUD operations programmatically in a Grid.

  1. AddRecordAsync - Adds a new record to the Grid.
  2. StartEditAsync - Starts edit the selected row.
  3. EndEditAsync - If Grid is in editable state, you can save a record by invoking endEdit.
  4. CloseEditAsync - Cancels edited state.
  5. DeleteRecordAsync - Delete a selected record.


Regards,
Sarvesh


Attachment: SfGridColumnModified_9742e381.zip


KH koilte hight March 18, 2023 10:35 AM UTC

Thank U.

but it did not worked with me.

i think there are some error on my way to do that.


So. I have another question. Please Help Me. 

How can use  DateRangePicker in Grid. Save data in database. with Add and Edit Mode. 

Thank you very much.



PS Prathap Senthil Syncfusion Team March 20, 2023 12:38 PM UTC

Thanks for the Update.

Query:” How can use DateRangePicker in Grid

We are glad to inform you that we have created a sample using the DateRangePicker in conjunction with the Grid for adding and editing operations using EditTemplatefeature. We have attached the code snippet and sample for your reference.

 

<SfGrid @ref="Grid" TValue="Order" AllowFiltering="true" AllowPaging="true" DataSource="@Orders" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })">

    <GridEvents OnActionBegin="OnActionBegin" TValue="Order"></GridEvents>

    <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true"></GridEditSettings>

   

 

        <GridColumn Field=@nameof(Order.OrderDate) HeaderText=" Order Date" Format="MM/dd/yyyy hh:mm tt"

                    TextAlign="TextAlign.Right" Width="250">

            <EditTemplate>

                @{

                    <SfDateRangePicker Placeholder="Choose a Range" Width="500" ShowClearButton="true"

                                       @bind-StartDate="StartDate" @bind-EndDate="EndDate" TValue="DateTime">

                        <DateRangePickerEvents TValue="DateTime" ValueChange="ValueChangeHandler">

                        </DateRangePickerEvents>

                    </SfDateRangePicker>

                }

            </EditTemplate>

        </GridColumn>

        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2"

                    TextAlign="TextAlign.Right" Width="120"></GridColumn>

    </GridColumns>

</SfGrid>

 

@code {

    private SfGrid<Order> Grid;

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public List<Order> Orders { get; set; }

    public async Task OnActionBegin(ActionEventArgs<Order> args)

    {

        if (args.RequestType == Syncfusion.Blazor.Grids.Action.Save)   // Triggers before save operation start for Add and Edit.

        {

 

            //Here you can customize your requirements.

            args.Data.OrderDate = StartDate;

 

        }

     

    }
  
public void ValueChangeHandler(RangePickerEventArgs<DateTime> args)

    {

        StartDate = args.StartDate;

        EndDate = args.EndDate;

    }
}


Reference:
https://blazor.syncfusion.com/documentation/datagrid/editing#event-trace-while-editing
https://blazor.syncfusion.com/documentation/daterangepicker/data-binding#two-way-data-binding

  


Query:” i think there are some errors on my way to do that

Before proceeding the reported issue, we kindly request that you provide a simple reproducible sample, or if possible, try modifying the previous attached sample to see if the issue can be reproduced there. We appreciate your cooperation and hope to resolve this issue for you as soon as possible.


Attachment: DataGridWithDataRangePicker_8aaa6858.zip


KH koilte hight replied to Prathap Senthil March 21, 2023 04:06 PM UTC

Thank you.

With all my respect and appreciation.


SG Suganya Gopinath Syncfusion Team March 22, 2023 03:35 AM UTC

Koilte, 

We hope the provided solution helped to solve the issue. 

If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.



Loader.
Up arrow icon