【问题标题】:Winforms code for datatable - what's the WPF equivalent?数据表的 Winforms 代码 - WPF 等效项是什么?
【发布时间】:2013-10-08 04:09:34
【问题描述】:

我在 Winforms 应用程序中有以下代码,它按预期工作:

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());
    }
}

我现在正在为此项目构建一个新的 WPF 界面,但以下内容不起作用 - 我应该如何处理这个问题?

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());
    }
}

我收到的错误在以下行:

dataSiteCollections.ItemsSource = dt;

这是:

无法将源类型“System.Data.DataTable”转换为目标类型 'System.Collections.IEnumerable'

【问题讨论】:

  • 尝试像这样插入.ToList();:dataSiteCollections.ItemsSource = dt.ToList();
  • @Tico 这只是给出错误'无法解析符号'ToList'

标签: c# .net wpf winforms


【解决方案1】:

试试这个:

dataSiteCollections.ItemsSource = dt.AsDataView();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多