Ibanez1408
Ibanez1408

Reputation: 5058

How to create a DataGrid ItemSource in an async task list

I need to get a list as an ItemSource for a DataGrid in wpf. I can get the result from my async method which is like so:

public async Task<List<ManualReadTag>> GetManuallyReadTags(ParameterManualTags model { ..... }

and I try to have its value displayed in a DataGrid in my MainWindow.xaml like so:

public partial class MainWindow : Window
{
    readonly ApplicationController _ac = new ApplicationController();
    private Task<List<ManualReadTag>> _manualReadTagList = null;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void BtnGEtManualCount_OnClick(object sender, RoutedEventArgs e)
    {
        GetManuallyReadTags();
    }

    private void GetManuallyReadTags()
    {
        var model = new ParameterManualTags
        {
            Lane = Convert.ToInt32(TxtLane.Text),
            Plaza = Convert.ToInt32(TxtLane),
            DateTo = DateTo.DisplayDate,
            DateFrom = DateFrom.DisplayDate
        };
         _manualReadTagList = _ac.GetManuallyReadTags(model);
        ViewingGrid.ItemsSource = _manualReadTagList;
    }
}

But on the ViewingGrid.ItemsSource = _manualReadTagList; it gives me an error of:

Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'System.Threading.Tasks.Task>' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?) TagReporting D:\Projects\Lane\Antenna_Reading\TagReporting\TagReporting\MainWindow.xaml.cs 38 Active

How can I use the result from my async Task method as an ItemSource for my datagrid? Thank you.

Upvotes: 0

Views: 377

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

Firstly, if GetManuallyReadTags is an async method it's not named very well, it should have an async suffix GetManuallyReadTagsAsync to make it obvious.

Secondly, it's ideal to await the async call.

private async Task GetManuallyReadTagsAsync()
{
    var model = new ParameterManualTags
    {
        Lane = Convert.ToInt32(TxtLane.Text),
        Plaza = Convert.ToInt32(TxtLane),
        DateTo = DateTo.DisplayDate,
        DateFrom = DateFrom.DisplayDate
    };

     _manualReadTagList = await _ac.GetManuallyReadTags(model);
    ViewingGrid.ItemsSource = _manualReadTagList;
}

You would also change the type of the _manualReadTagList to

private List<ManualReadTag> _manualReadTagList;

and finally call GetManuallyReadTagsAsync() in an async event handler:

private async void BtnGEtManualCount_OnClick(object sender, RoutedEventArgs e)
{
    await GetManuallyReadTagsAsync();
}

Upvotes: 1

Related Questions