简体   繁体   中英

Winforms code for datatable - what's the WPF equivalent?

I have the following code in a Winforms application, which works as expected:

private void btnFetchCollections_Click(object sender, EventArgs e)
{
    try
    {
        var scDal = new SiteCollectionDal();
        var dt = new DataTable();

        List<SiteCollectionEntity> siteCollections = scDal.FetchSiteCollections();

        dt.Columns.Add(new DataColumn("Site Name", typeof(string)));

        foreach (SiteCollectionEntity siteCollectionEntity in siteCollections)
        {
            DataRow row = dt.NewRow();

            row["Site Name"] = siteCollectionEntity.Url;

            dt.Rows.Add(row);

            dt.AcceptChanges();
        }

        dataSiteCollections.DataSource = dt;

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

I'm now building a new WPF interface for this project, and the following doesn't work - how should I be approaching this?

private void btnFetchSiteCollections_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var scDal = new SiteCollectionDal();
        var dt = new DataTable();

        List<SiteCollectionEntity> siteCollections = scDal.FetchSiteCollections();

        dt.Columns.Add(new DataColumn("Site Name", typeof(string)));

        foreach (SiteCollectionEntity siteCollectionEntity in siteCollections)
        {
            DataRow row = dt.NewRow();

            row["Site Name"] = siteCollectionEntity.Url;

            dt.Rows.Add(row);

            dt.AcceptChanges();
        }

        dataSiteCollections.ItemsSource = dt;

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

The error I'm receiving is on the following line:

dataSiteCollections.ItemsSource = dt;

Which is:

Cannot convert source type 'System.Data.DataTable' to target type 'System.Collections.IEnumerable'

尝试这个:

dataSiteCollections.ItemsSource = dt.AsDataView();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM