数据库中的数据显示在表单上。怎么了?
我制作存储库、表格和一些方法。我使用 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;
}
}
白衣染霜花
呼唤远方
相关分类