Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Connects the DevExpress WinForms Data Grid to a .NET Core service.

License

NotificationsYou must be signed in to change notification settings

DevExpress-Examples/connect-winforms-grid-to-dotnetcore-service

Repository files navigation

Connect the DevExpress WinForms Data Grid to a .NET Core Service

Please readthe blog post for details about this sample.

Prerequisites

Getting Started

  1. OpenNetCoreServiceAll.sln.Register a DevExpress NuGet feed in the Visual Studio IDE. Skip this step if you have already registered your DevExpress NuGet feed.

  2. Restore NuGet packages in the solution:

    Restore NuGet Packages in the Solution

  3. Run theDataService project. Right-click DataService in the Solution Explorer and selectDebug |Start New Instance in the menu. Your default web browser will open.

    IMPORTANT

    Do not close the web browser.

  4. To initialize sample data when you run the service for the first time, navigate tohttp://localhost:5146/api/populateTestData in the open web browser. You will see the following message:"Data populated successfully".

  5. Run theWinForms.Client project. Right-click WinForms.Client in the Solution Explorer and selectDebug |Start New Instance in the menu.

  6. You can scroll to the end of the data list in the grid and observe more data being loaded. You can sort by clicking column headers. TheOutput tool window within Visual Studio will display information about load status from both running processes. The animation below displays results:

    WinForms Client

Implementation Details

The Backend: an ASP.NET Core WebAPI service using Entity Framework Core

The backend project is calledDataService and it was created using the standard ASP.NET Core WebAPI template. There are two endpoint handlers in the service, one to generate some test data and the other to query data.

The second handler, at the URL /data/OrderItems, accepts several optional parameters (to supportskip,take, andsort features). The code queries data from the Entity Framework Core database context and uses standardIQueryable<T> based helpers to implement data shaping functionality. TheTotalCount field is returned together with data and is used on the client side to determine the total amount of data available for the request.

app.MapGet("/data/OrderItems",async(DataServiceDbContextdbContext,intskip=0,inttake=20,stringsortField="Id",boolsortAscending=true)=>{varsource=dbContext.OrderItems.AsQueryable().OrderBy(sortField+(sortAscending?" ascending":" descending"));varitems=awaitsource.Skip(skip).Take(take).ToListAsync();vartotalCount=awaitdbContext.OrderItems.CountAsync();returnResults.Ok(new{Items=items,TotalCount=totalCount});});

The Frontend: a Windows Forms app with a DevExpress Data Grid

In theMainForm of the Windows Forms application, the DevExpress GridControl control is bound to aVirtualServerModeSource instance (a collection ofOrderItem objects). To fetch data, the VirtualServerModeSource handles the following events:

  • ConfigurationChanged - Fires when the grid changes relevant parts of its runtime configuration in response to user interaction (for example, when the user clicks a column header to apply sort operations).
  • MoreRows - Fires when an initial fetch operation returns a result, which indicates that more data is available. In this instance, the grid attempts to retrieve additional data rows if and when the user scrolls to the bottom of the currently loaded data set.

In this example, the data loaded from the backend is encoded as JSON.DataFetchResult models the structure of the response provided by the backend endpoint, including theTotalCount property:

publicclassDataFetchResult{publicList<OrderItem>Items{get;set;}=null!;publicintTotalCount{get;set;}}

TheGetRowsAsync method handles retrieved data. The method is invoked during the initial load (from theConfigurationChanged handler) and subsequent loads (from theMoreRows handler). Data is fetched usingHttpClient, with skip, take, and sorting properties passed as URL parameters. The results are deserialized from JSON and returned along with themoreRowsAvailable flag:

publicTask<VirtualServerModeRowsTaskResult>GetRowsAsync(VirtualServerModeRowsEventArgse){returnTask.Run(async()=>{usingvarclient=newHttpClient();varresponse=awaitclient.GetAsync($"{System.Configuration.ConfigurationManager.AppSettings["baseUrl"]}/data/OrderItems?skip={e.CurrentRowCount}&take={BatchSize}&sortField={SortField}&sortAscending={SortAscending}");response.EnsureSuccessStatusCode();varresponseBody=awaitresponse.Content.ReadAsStringAsync();vardataFetchResult=JsonSerializer.Deserialize<DataFetchResult>(responseBody,newJsonSerializerOptions{PropertyNameCaseInsensitive=true});if(dataFetchResultisnull)returnnewVirtualServerModeRowsTaskResult();varmoreRowsAvailable=e.CurrentRowCount+dataFetchResult.Items.Count<dataFetchResult.TotalCount;returnnewVirtualServerModeRowsTaskResult(dataFetchResult.Items,moreRowsAvailable);},e.CancellationToken);}

Related Examples

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)

About

Connects the DevExpress WinForms Data Grid to a .NET Core service.

Topics

Resources

License

Stars

Watchers

Forks

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp