c# - 在 WPF 应用程序的 DataGrid 中显示 SQL 查询的结果
问题描述
查询的结果在 SqlDataReader 中,它可以有灵活的列数和行数。
string mySQLQuery= "select * from myTable";
SqlCommand myTableCommand = new SqlCommand(mySQLQuery, MyConnection);
SqlDataReader myReader = null;
myReader = myTableCommand.ExecuteReader();
我想做的是在 DataGrid 中显示结果。.xaml 部分是这样的:
<DataGrid Name="myDataGrid" SelectionMode="Extended" SelectionUnit="Cell" AutoGenerateColumns="True" AlternatingRowBackground="LightCyan"
ItemsSource="{Binding}" IsEnabled="True" IsReadOnly="True" Background="WhiteSmoke" Margin="13,27,8,110" CanUserSortColumns="True">
</DataGrid>
.xaml.cs 部分中用于将我的表的值显示到 DataGrid 中的以下代码块是完全假设的,只是为了阐明我想要做什么:
// suppose that I have read the list of headers (column names)
// and suppose a button is clicked and an event is triggered and these codes are fit into that event
List<string> myHeaders = new List<string>() { "ID" , "Name" , "Country" , "City" };
myDataGrid.headers= myHeaders; // no method called "header" in reality
While (myReader.Read())
{
myDataGrid.RowValues = myReader // no method called "RowValues" in reality
}
我更喜欢没有单独的类来管理 DataGrid 的每一列的解决方案,因为这样很难拥有灵活的列数。显然我希望我的结果是这样的:
ID | Name | Country | City
------------------------------------
123 | John | England | London
------------------------------------
456 | Jane | Ireland | Dublin
... ... ... ...
此链接中的答案都没有帮助: How to display SQL search results in a datagrid using WPF
解决方案
解决方案:
感谢“user1672994”,这个解决方案现在可以工作了:
string mySQLQuery= "select * from myTable";
SqlCommand myTableCommand = new SqlCommand(mySQLQuery, MyConnection);
DataTable dt = new DataTable();
SqlDataAdapter a = new SqlDataAdapter(myTableCommand );
a.Fill(dt);
myDataGrid.ItemsSource = dt.DefaultView;
推荐阅读
- java - Maven WAR:为不同的包拆分类 JAR
- java - REST 控制器中 RequestParam 的正确方法
- python - 如何对项目进行分页
- javascript - 使用下一个承诺中的返回值使用承诺编写一个while循环
- visual-studio - VS 2019 安装“Microsoft Visual Studio 安装程序项目”失败
- javascript - 在输入区域文本中动态添加输入
- vim - 将当前颜色保存为 vim 中的可加载颜色方案
- java - 如何暂停和重新启动自动 ejb
- python - 将二进制数据添加到 django rest 框架 API
- vue.js - 如何修改自动完成以便我只能搜索 1 个单词?