DropDown Dynamic loadDate

2 Answers 23 Views
DropDownList
hans
Top achievements
Rank 1
Iron
hans asked on 29 Nov 2024, 10:57 AM
I had a question about the Dropdown element, I saw how to search for it, but I couldn't find it for dynamic
    public SearchWarehouseNP()
    {
        InitializeComponent();
        dropdownSettlement.DropDownStyle = RadDropDownStyle.DropDown;
        dropdownSettlement.AutoCompleteMode = AutoCompleteMode.Suggest;

        dropdownSettlement.DropDownListElement.AutoCompleteSuggest = new CustomAutoCompleteSuggestHelperUpdate(
            dropdownSettlement.DropDownListElement,
            async query =>
            {
                if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
                    return Enumerable.Empty<DescriptionTextListDataItem>();

                var response = await _searchSettlementService.GetCityData(query);
                if (response.success && response.data.Any())
                {
                    return response.data.First().Addresses.Select(a => new DescriptionTextListDataItem
                    {
                        Text = $"{a.MainDescription} ({a.Area})",
                        Value = a.MainDescription,
                        DescriptionText = a.Area
                    });
                }

                return Enumerable.Empty<DescriptionTextListDataItem>();
            }
        );

        dropdownSettlement.SelectedIndexChanged += (s, e) =>
        {
            if (dropdownSettlement.SelectedItem is DescriptionTextListDataItem selectedItem)
            {
                Console.WriteLine($"Выбрано: {selectedItem.Text} ({selectedItem.Value})");
            }
        };
    }
}
The problem is that the data is not stored in Items
Console.WriteLine empty

using Telerik.WinControls.UI;

namespace NovaPostOrderManager.Helpers;

public class CustomAutoCompleteSuggestHelperUpdate : AutoCompleteSuggestHelper
{
    private readonly Func<string, Task<IEnumerable<DescriptionTextListDataItem>>> _fetchDataAsync;
    private CancellationTokenSource _cts = new();

    public CustomAutoCompleteSuggestHelperUpdate(RadDropDownListElement owner, Func<string, Task<IEnumerable<DescriptionTextListDataItem>>> fetchDataAsync)
        : base(owner)
    {
        _fetchDataAsync = fetchDataAsync;
    }

    protected override async void SyncItemsCore()
    {
        // Текущий текст из поля ввода
        string currentInput = Filter;

        // Проверяем, нужно ли загружать данные
        if (string.IsNullOrWhiteSpace(currentInput) || currentInput.Length < 3)
        {
            DropDownList.ListElement.Items.Clear();
            DropDownList.ClosePopup();
            return;
        }

        // Отменяем предыдущий запрос
        _cts.Cancel();
        _cts = new CancellationTokenSource();

        try
        {
            // Задержка перед началом запроса
            await Task.Delay(300, _cts.Token);

            // Загружаем данные
            var items = await _fetchDataAsync(currentInput);

            _cts.Token.ThrowIfCancellationRequested();

            DropDownList.ListElement.BeginUpdate();
            DropDownList.ListElement.Items.Clear();

            // Добавляем элементы в выпадающий список
            foreach (var item in items)
            {
                DropDownList.ListElement.Items.Add(item);
            }

            DropDownList.ListElement.EndUpdate();

            if (DropDownList.ListElement.Items.Count > 0)
            {
                DropDownList.ShowPopup(); // Показываем список, если есть элементы
            }
            else
            {
                DropDownList.ClosePopup();
            }
        }
        catch (TaskCanceledException)
        {
            // Запрос был отменён — игнорируем
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Ошибка загрузки данных: {ex.Message}");
        }
    }

    protected override bool DefaultFilter(RadListDataItem item)
    {
        if (item is not DescriptionTextListDataItem descriptionItem)
            return base.DefaultFilter(item);

        return descriptionItem.Text.Contains(Filter, StringComparison.CurrentCultureIgnoreCase) ||
               descriptionItem.DescriptionText.Contains(Filter, StringComparison.CurrentCultureIgnoreCase);
    }
}

2 Answers, 1 is accepted

Sort by
1
Dinko | Tech Support Engineer
Telerik team
answered on 29 Nov 2024, 12:37 PM

Hi hans,

I appreciate your interest in our RadDropDownList control for WinForms. I have checked the code but it's still unclear to me what is your requirement here. May I ask you to elaborate more on your question. If you can isolate your approach in a sample project with dummy data, that would be great. This way I can debug the code and try to find a suitable solution for your scenario.

I am looking forward to your reply.

Regards,
Dinko | Tech Support Engineer
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

0
hans
Top achievements
Rank 1
Iron
answered on 29 Nov 2024, 01:25 PM
https://drive.google.com/drive/folders/1xSnBc-VEk-9Wa1UH9CZPlGIrVXTF-h0t?usp=sharing
Dinko | Tech Support Engineer
Telerik team
commented on 29 Nov 2024, 02:41 PM

Thank you for the project, however, I will need some guidance to reproduce this behavior. May I ask you to send steps that I will follow and observe what is the current behavior and what you are trying to implement in your application? When I run the project, I see some logic form with empty dropdown lists.
hans
Top achievements
Rank 1
Iron
commented on 29 Nov 2024, 03:35 PM

1) after starting the project there is a DropDownList very first
2) it needs to write "Київ" in Ukrainian
3) after that a problem arises, items are not loaded correctly and SeelctedItem is not selected
4) and from the second query Items is selected but it is empty
hans
Top achievements
Rank 1
Iron
commented on 03 Dec 2024, 08:30 AM | edited

are you having any success?
Dinko | Tech Support Engineer
Telerik team
commented on 03 Dec 2024, 09:56 AM

The provided steps are greatly appreciated. Upon debugging this behavior, the Filter property in the CustomAutoCompleteSuggestHelper3.SyncItemsCore is executed too early. You can observe that if you type "Київ" and then add an empty space, the dropdown will pop up and the data. 

What you can do is move the logic in the ApplyFilterToDropDown() method. Here is the whole class:

public class CustomAutoCompleteSuggestHelper3 : AutoCompleteSuggestHelper
{
    private readonly Func<string, Task<IEnumerable<DescriptionTextListDataItem>>> _fetchDataAsync;

    public CustomAutoCompleteSuggestHelper3(RadDropDownListElement owner, Func<string, Task<IEnumerable<DescriptionTextListDataItem>>> fetchDataAsync)
        : base(owner)
    {
        _fetchDataAsync = fetchDataAsync;
    }

    public override async void ApplyFilterToDropDown(string filter)
    {
        base.ApplyFilterToDropDown(filter);

        string currentInput = Filter;
        if (string.IsNullOrWhiteSpace(currentInput) || currentInput.Length < 3)
        {
            DropDownList.ListElement.Items.Clear();
            DropDownList.ClosePopup();
            return;
        }

        try
        {
            // Получаем данные
            var items = await _fetchDataAsync(currentInput);

            DropDownList.ListElement.BeginUpdate();
            DropDownList.ListElement.Items.Clear();

            foreach (var item in items)
            {
                DropDownList.ListElement.Items.Add(item);
            }

            DropDownList.ListElement.EndUpdate();

            if (DropDownList.ListElement.Items.Count > 0)
            {
                DropDownList.ShowPopup(); // Показываем выпадающий список
            }
            else
            {
                DropDownList.ClosePopup();
            }
        }
        catch (TaskCanceledException)
        {
            // Игнорируем отменённые запросы
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Ошибка загрузки данных: {ex.Message}");
        }
    }

    protected override bool DefaultFilter(RadListDataItem item)
    {
        if (item is not DescriptionTextListDataItem descriptionItem)
            return base.DefaultFilter(item);

        return descriptionItem.Text.Contains(Filter, StringComparison.CurrentCultureIgnoreCase) ||
               descriptionItem.DescriptionText.Contains(Filter, StringComparison.CurrentCultureIgnoreCase);
    }
}

I hope that this approach will work in your project. 

Tags
DropDownList
Asked by
hans
Top achievements
Rank 1
Iron
Answers by
Dinko | Tech Support Engineer
Telerik team
hans
Top achievements
Rank 1
Iron
Share this question
or