我看到了一些与我的问题相关的答案。我被尝试了答案,但我仍然无法解决这个问题。
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 :(得分: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>
希望这会有所帮助