2011-12-17 59 views
0

我看到了一些與我的問題有關的答案。我試過這個答案,但我仍然無法解決這個問題。將數據表添加到WPF中的DataGrid

private void btn_View_Click(object sender, RoutedEventArgs e) 
{ 
    try 
    { 
    DataTable objDataTable = this.FillDepartment(); 
    this.dataGrid1.ItemsSource = objDataTable.DefaultView; 
    } 
    catch (Exception ex) 
    { 
    MessageBox.Show(ex.Message); 
    } 
} 

private DataTable FillDepartment() 
{ 
    try 
    { 
    Departments objDepartments = new DepartmentServices().GetAllDept(); 
    DataTable objDataTable = new DataTable(); 

    objDataTable.Columns.Add("Department No"); 
    objDataTable.Columns.Add("Department Name"); 
    objDataTable.Columns.Add("Location"); 

    foreach (Department department in objDepartments) 
    { 
     DataRow objDataRow = objDataTable.NewRow(); 

     objDataRow[0] = department.DepNo; 
     objDataRow[1] = department.Name; 
     objDataRow[2] = department.Loc; 

     objDataTable.Rows.Add(objDataRow); 
    } 

    return objDataTable; 
    } 
    catch (Exception) 
    { 

    throw; 
    } 
} 

使用斷點並通過代碼我看到objDataTable對象返回帶有插入到數據庫中的值的對象。但我不能將這些行添加到DataGrid。希望你們能幫我解決這個問題。

回答

0

我會爲您的問題建議以下解決方案。

使用DefaultView是因爲DataTable沒有實現IEnumerable並綁定到它。

public static readonly DependencyProperty ObjDataTableDefaultViewProperty = 
    DependencyProperty.Register("ObjDataTableDefaultView", typeof(System.Data.DataView), typeof(Window2), new FrameworkPropertyMetadata()); 

public System.Data.DataView ObjDataTableDefaultView { 
    get { return (System.Data.DataView)GetValue(ObjDataTableDefaultViewProperty); } 
    set { SetValue(ObjDataTableDefaultViewProperty, value); } 
} 

private void CreateObjDataTable() 
{ 
    try 
    { 
    ObjDataTableDefaultView = this.FillDepartment().DefaultView; 
    } 
    catch (Exception ex) 
    { 
    MessageBox.Show(ex.Message); 
    } 
} 

的XAML代碼

<Window x:Class="Spielwiese.Window2" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="Spielwiese" Height="300" Width="300" 
     x:Name="uc"> 
<Grid> 
    <DataGrid x:Name="dataGrid1" 
      AutoGenerateColumns="True" 
      ItemsSource="{Binding ObjDataTableDefaultView, ElementName=uc, Mode=OneWay}"/> 
</Grid> 
</Window> 

希望這有助於

+0

好的,謝謝ü。我會試試這個。 – Shashika 2011-12-17 13:30:48

相關問題