wpf应用程序中出现的数据gridview绑定错误

时间:2014-01-15 07:23:01

标签: wpf wpfdatagrid

我是WPF应用程序的初学者,刚才我在WPF allplication中启动了一个小应用程序

因为我有一个网格视图..在加载页面时我想将一些数据填充到网格视图..所以我在我的表单加载事件中给出了代码:

Dim adapter As SqlDataAdapter
Dim dt1 As DataTabl
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
  Dim con As SqlConnection = New SqlConnection("Data Source=SUPPORT2\SUPPORT2;Initial Catalog=Registry;Persist Security Info=True;User ID=sa;password=solutions")
        con.Open()
        Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
        adapter = New SqlDataAdapter("select c.cid,c.CompanyName,d.dtId,d.dtName as Department,d.dtPhone as Phone,d.dtEmail as Email from CompanyMaster_tbl c join  DepartmentMaster_tbl d on c.Cid=d.cId order by cid", con)
        dt1 = New DataTable
        adapter.Fill(dt1) 'Filling dt with the information from the DB
        DataGrid1.ItemsSource = dt1

在运行代码时,我在此行中收到错误: DataGrid1.ItemsSource = dt1
错误: 无法将类型为“System.Data.DataTable”的对象强制转换为“System.Collections.IEnumerable”。   请告诉我如何在WPF应用程序中编写代码

1 个答案:

答案 0 :(得分:1)

试试这样:

DataGrid1.ItemsSource = dt1.DefaultView;

DefaultView的类型为DataView,它实现了IEnumerable

这是我用于测试的完整示例,它是C#代码,我希望你不介意:

DataTable table = new DataTable();
table.Columns.Add("Col1 - int", typeof(int));
table.Columns.Add("Col2 - string", typeof(string));

table.Rows.Add(new object[] {1, "Smith"});
table.Rows.Add(new object[] {2, "John"});

grid.ItemsSource = table.DefaultView;

这是XAML中的DataGrid声明:

<DataGrid Name="grid" />