Skip to content

Commit 0c7f01e

Browse files
NansiYanchevaikoevskaTsvetomir-Hr
authored
docs(Grid): Add KB for programmatically row selection and scroll to row (#2484)
* docs(Grid): Add KB for programmatically row selection and scroll to row * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Iva Stefanova Koevska-Atanasova <koevska@progress.com> * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Iva Stefanova Koevska-Atanasova <koevska@progress.com> * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Tsvetomir Hristov <106250052+Tsvetomir-Hr@users.noreply.github.com> * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Tsvetomir Hristov <106250052+Tsvetomir-Hr@users.noreply.github.com> * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Tsvetomir Hristov <106250052+Tsvetomir-Hr@users.noreply.github.com> * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Tsvetomir Hristov <106250052+Tsvetomir-Hr@users.noreply.github.com> * Update knowledge-base/grid-scroll-to-selected-row.md Co-authored-by: Tsvetomir Hristov <106250052+Tsvetomir-Hr@users.noreply.github.com> * docs(Grid): update after review --------- Co-authored-by: Iva Stefanova Koevska-Atanasova <koevska@progress.com> Co-authored-by: Tsvetomir Hristov <106250052+Tsvetomir-Hr@users.noreply.github.com>
1 parent 06abbed commit 0c7f01e

File tree

1 file changed

+261
-4
lines changed

1 file changed

+261
-4
lines changed

knowledge-base/grid-scroll-to-selected-row.md

Lines changed: 261 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,268 @@ res_type: kb
2222

2323

2424
## Description
25-
I would like to pre-select a row when the page is loaded, and I would like to show the grid with that row scrolled to the top, or sorted to appear on top.
25+
26+
I want to programmatically [select a row in the Grid]({%slug grid-selection-row%}) based on specific conditions in my code. Once selected, I’d like the Grid to automatically scroll to that row so it’s visible to the user.
2627

2728
## Solution
28-
You can find a selected row in the grid markup by the `k-selected` CSS class it has, and use a bit of JavaScript to scroll to it - browsers provide the `scrollIntoView()` method for that.
2929

30-
With **row virtualization**, however, the selected row may not be rendered. That is why you need to find its position and scroll to it through the `Skip` parameter of the Grid.
30+
The solution to select programatically a row in Grid and scroll to that selected row, depends on the Grid configuration.
31+
32+
### Grid with **[paging feature]({%slug components/grid/features/paging%})**
33+
34+
1. Ensure the Grid is on the same page as the selected row.
35+
1. Invoke a JavaScript to make the browser scroll to the selected row into view. The browsers provide the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView" target="_blank">`scrollIntoView()` method</a> that does the scrolling. You can find a selected row in the grid markup by its `k-selected` CSS class.
36+
37+
### Grid with **[virtualization feature]({%slug components/grid/virtual-scrolling%})**
38+
39+
1. Use the [Grid state]({%slug grid-state%}).
40+
1. Set the [`Skip` parameter]({%slug grid-state%}#information-in-the-grid-state) to the index of the item in the current data collection.
41+
42+
## Example
43+
44+
The example below offers comments in the code on some possible improvements.
45+
46+
>caption Select a Row in Grid Programmatically and Scroll to the Row
47+
48+
````CSHTML
49+
@using Telerik.DataSource
50+
@using Telerik.DataSource.Extensions
51+
@inject IJSRuntime JsInterop
52+
53+
54+
@* Move JavaScript code to a separate JS file in production *@
55+
<script suppress-error="BL9992">
56+
window.scrollToSelectedRow = function () {
57+
var selectedRow = document.querySelector('.k-selected');
58+
if (selectedRow) {
59+
selectedRow.scrollIntoView();
60+
}
61+
}
62+
</script>
63+
64+
<script suppress-error="BL9992">
65+
window.scrollToFirstRow = function () {
66+
var selectedRow = document.querySelector('.k-table-row.k-master-row');
67+
if (selectedRow) {
68+
selectedRow.scrollIntoView();
69+
}
70+
}
71+
</script>
72+
73+
<br/>
74+
<h2>Grid with Paging</h2>
75+
<TelerikAutoComplete Data="@Employees"
76+
Value="@SelectedEmployeeInPageMode"
77+
Placeholder="Search an employee..."
78+
ShowClearButton="true"
79+
DebounceDelay="500"
80+
Width="300px"
81+
FilterOperator="StringFilterOperator.Contains"
82+
ValueChanged="@HandleSelectedRowWithPageMode">
83+
</TelerikAutoComplete>
84+
85+
<TelerikGrid Data=@GridData
86+
SelectionMode="@GridSelectionMode.Single"
87+
@bind-SelectedItems="@SelectedItemsInPageMode"
88+
Pageable="true"
89+
Page="@PageInPageMode"
90+
PageSize="@PageSizeInPageMode"
91+
Height="300px">
92+
<GridColumns>
93+
<GridColumn Field=@nameof(Employee.Name) />
94+
<GridColumn Field=@nameof(Employee.Team) Title="Team" />
95+
</GridColumns>
96+
</TelerikGrid>
97+
98+
<br/>
99+
<h2>Grid with Virtualization</h2>
100+
<TelerikAutoComplete Data="@Employees"
101+
Value="@SelectedEmployeeInVirtualization"
102+
Placeholder="Search an employee..."
103+
ShowClearButton="true"
104+
DebounceDelay="500"
105+
Width="300px"
106+
FilterOperator="StringFilterOperator.Contains"
107+
ValueChanged="@HandleSelectedRowWithVirtualization">
108+
</TelerikAutoComplete>
109+
110+
<TelerikGrid @ref="@GridRef"
111+
TItem="@Employee"
112+
OnRead="@ReadItems"
113+
SelectionMode="GridSelectionMode.Single"
114+
@bind-SelectedItems="@SelectedItemsInVirtualization"
115+
Sortable="true"
116+
ScrollMode="@GridScrollMode.Virtual"
117+
RowHeight="40"
118+
PageSize="@PageSizeInVirtualization"
119+
Height="300px">
120+
<GridColumns>
121+
<GridColumn Field=@nameof(Employee.Name) />
122+
<GridColumn Field=@nameof(Employee.Team) Title="Team" />
123+
</GridColumns>
124+
</TelerikGrid>
125+
126+
127+
@code {
128+
#region Parameters
129+
130+
private TelerikGrid<Employee>? GridRef { get; set; }
131+
132+
private List<Employee> GridData { get; set; } = new();
133+
private List<string> Employees { get; set; } = new();
134+
135+
private IEnumerable<Employee> SelectedItemsInPageMode { get; set; } = Enumerable.Empty<Employee>();
136+
private IEnumerable<Employee> SelectedItemsInVirtualization { get; set; } = Enumerable.Empty<Employee>();
137+
138+
private string SelectedEmployeeInPageMode { get; set; } = string.Empty;
139+
private string SelectedEmployeeInVirtualization { get; set; } = string.Empty;
140+
141+
private int PageInPageMode { get; set; } = 1;
142+
private int PageSizeInPageMode { get; set; } = 30;
143+
private int PageSizeInVirtualization { get; set; } = 20;
144+
145+
private int GridDataCount { get; set; }
146+
private int AllDataCount { get; set; }
147+
148+
#endregion Parameters
149+
150+
#region Event Handlers
151+
152+
private async Task HandleSelectedRowWithPageMode(string newValue)
153+
{
154+
SelectedEmployeeInPageMode = newValue;
155+
156+
if (!string.IsNullOrEmpty(SelectedEmployeeInPageMode))
157+
{
158+
SelectedItemsInPageMode = GridData.Where(item => item.Name == SelectedEmployeeInPageMode).ToList();
159+
160+
//Find and set the page where is the selected item
161+
int itemIndex = GridData.IndexOf(SelectedItemsInPageMode.First());
162+
PageInPageMode = (int)Math.Ceiling((double)(itemIndex + 1) / PageSizeInPageMode);
163+
164+
await Task.Delay(20);//Simulate network delay so the page can be set and render in the browser
165+
166+
await JsInterop.InvokeVoidAsync("scrollToSelectedRow");
167+
}
168+
else
169+
{
170+
SelectedItemsInPageMode = new List<Employee>();
171+
await Task.Delay(20);//Simulate network delay
172+
await JsInterop.InvokeVoidAsync("scrollToFirstRow");
173+
}
174+
}
175+
176+
private async Task HandleSelectedRowWithVirtualization(string newValue)
177+
{
178+
SelectedEmployeeInVirtualization = newValue;
179+
180+
int targetItemIndex;
181+
182+
if (!string.IsNullOrEmpty(SelectedEmployeeInVirtualization))
183+
{
184+
SelectedItemsInVirtualization = GridData.Where(item => item.Name == SelectedEmployeeInVirtualization).ToList();
185+
targetItemIndex = GridData.IndexOf(SelectedItemsInVirtualization.First());
186+
}
187+
else
188+
{
189+
SelectedItemsInVirtualization = new List<Employee>();
190+
targetItemIndex = GridData.IndexOf(GridData.First());
191+
}
192+
await SetSkip(targetItemIndex, SelectedItemsInVirtualization);
193+
}
194+
195+
#endregion Event Handlers
196+
197+
#region Methods
198+
199+
private async Task SetSkip(int skip)
200+
{
201+
await SetSkip(skip, null);
202+
}
203+
204+
private async Task SetSkip(int skip, IEnumerable<Employee> itemsToSelect)
205+
{
206+
if (GridRef != null)
207+
{
208+
var state = GridRef.GetState();
209+
if (itemsToSelect != null)
210+
{
211+
state.SelectedItems = (ICollection<Employee>)itemsToSelect;
212+
}
213+
state.Skip = ValidateSkip(skip);
214+
await GridRef.SetStateAsync(state);
215+
}
216+
}
217+
218+
private int ValidateSkip(int desiredSkip)
219+
{
220+
if (desiredSkip < 0) return 0;
221+
int itemsThatFitPerPage = 7;
222+
bool isInvalidSkip = GridDataCount < itemsThatFitPerPage;
223+
return isInvalidSkip ? AllDataCount - itemsThatFitPerPage : desiredSkip;
224+
}
225+
226+
#endregion Methods
227+
228+
#region Life Cycle Methods
229+
230+
protected override async Task OnInitializedAsync()
231+
{
232+
GridData = GenerateData();
233+
Employees = GridData.Select(e => e.Name).ToList();
234+
}
235+
236+
#endregion Life Cycle Methods
237+
238+
#region Data Generation
239+
240+
protected async Task ReadItems(GridReadEventArgs args)
241+
{
242+
var datasourceResult = GridData.ToDataSourceResult(args.Request);
243+
var data = ((IEnumerable<Employee>)datasourceResult.Data).ToList();
244+
args.Data = data;
245+
args.Total = AllDataCount = datasourceResult.Total;
246+
GridDataCount = data.Count;
247+
248+
//See more about why this is done here https://docs.telerik.com/blazor-ui/knowledge-base/grid-large-skip-breaks-virtualization
249+
int allowedSkip = ValidateSkip(args.Request.Skip);
250+
if (allowedSkip != args.Request.Skip)
251+
{
252+
await SetSkip(allowedSkip);
253+
}
254+
}
255+
256+
private List<Employee> GenerateData()
257+
{
258+
List<Employee> data = new List<Employee>();
259+
for (int i = 1; i <= 100; i++)
260+
{
261+
data.Add(new Employee()
262+
{
263+
EmployeeId = i,
264+
Name = "Employee " + i.ToString(),
265+
Team = "Team " + i % 3
266+
});
267+
}
268+
return data;
269+
}
270+
271+
#endregion Data Generation
272+
273+
#region Models
274+
275+
public class Employee
276+
{
277+
public int EmployeeId { get; set; }
278+
public string Name { get; set; }
279+
public string Team { get; set; }
280+
}
281+
282+
#endregion Models
283+
}
284+
````
31285

32-
You can find examples in the following sample project: https://github.com/telerik/blazor-ui/tree/master/grid/scroll-to-selected-row
286+
## See Also
287+
* [Grid Row Selection]({%slug grid-selection-row%})
288+
* [Grid paging feature]({%slug components/grid/features/paging%})
289+
* [Grid virtualization feature]({%slug components/grid/virtual-scrolling%})

0 commit comments

Comments
 (0)