WPF DataGrid中的数据绑定未显示在窗体上

时间:2019-04-20 10:19:41

标签: c# database wpf

从表单上的数据库显示的数据。怎么了?

我制作存储库,表格和几种方法。我使用use SQLite,并希望以简单查询的形式显示结果,例如SELECT id,NAME FROM Students 我在带有代码的表单上放置了按钮

private void Button_Click(object sender, RoutedEventArgs e)
        {
            var repo = new StudentsRepository();
            var res = repo.GetAll();

            DataTable dt = new DataTable("students");
            DataGrid1.ItemsSource = dt.DefaultView;
        }

表单具有DataGrid和2列,但是我不了解为什么表单上没有显示结果

<Grid>
        <DataGrid x:Name="DataGrid1" AutoGenerateColumns="true"  HorizontalAlignment="Left" Height="352" Margin="10,10,0,0" VerticalAlignment="Top" Width="758" SelectionChanged="DataGrid_SelectionChanged">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding id}" Width="100" Header="Id"/>
            <DataGridTextColumn Binding="{Binding Name}" Width="100" Header="Name"/>
        </DataGrid.Columns>
        </DataGrid>
        <Button x:Name="ShowDataButton" Content="Show_Data" HorizontalAlignment="Left" Height="31" Margin="64,367,0,0" VerticalAlignment="Top" Width="161" Click="Button_Click"/>
    </Grid>

public class StudentsRepository: IRepository<StudentEntity>
    {
        private string GET_ALL_QUERY = "SELECT id, Name FROM Students";
        private SqliteContext DbContext { get; }

        public StudentsRepository()
        {
            DbContext = new SqliteContext();
        }
        public async Task<IList<StudentEntity>> GetAll()
        {
            var dataTable = new DataTable("Students");
            using (var conn = await DbContext.GetConnection())
            {
                var da = new SQLiteDataAdapter(GET_ALL_QUERY, conn);
                da.Fill(dataTable);

                conn.Close();
            }

            var studList = new List<StudentEntity>();
            foreach (DataRow row in dataTable.Rows)
            {
                studList.Add(new StudentEntity(row));
            }

            return studList;
        }
    }

2 个答案:

答案 0 :(得分:0)

如何?

public async Task<DataTable> GetDataTable()
{
    var dataTable = new DataTable("Students");
    using (var conn = await DbContext.GetConnection())
    {
        var da = new SQLiteDataAdapter(GET_ALL_QUERY, conn);
        da.Fill(dataTable);
        conn.Close();
    }
    return dataTable;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    var repo = new StudentsRepository();
    var res = repo.GetDataTable();
    DataGrid1.ItemsSource = res.Result.AsDataView();
}

希望这会有所帮助〜

已更新: 抱歉,函数返回类型是task,因此它不是实际数据,它将这样做:res.Result.AsDataView();

答案 1 :(得分:0)

在您的DataGrid上设置:

    AutoGenerateColumns="False"

然后更改:

DataGrid1.ItemsSource = dt.DefaultView

收件人:

DataGrid1.DataContext = dt.DefaultView

在WPF中,将绑定与定义的列一起使用要求您设置DataContext而不是ItemSource。就个人而言,在从数据库中提取数据并在DataGrid中显示数据时,我一直都使用.ToList(),因此我无法对DataTable的其余代码发表评论。