在wpf应用程序的datagrid中显示sql查询的结果

ybzsozfc  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(586)

查询的结果在sqldatareader中,它可以具有灵活的列数和行数。

  1. string mySQLQuery= "select * from myTable";
  2. SqlCommand myTableCommand = new SqlCommand(mySQLQuery, MyConnection);
  3. SqlDataReader myReader = null;
  4. myReader = myTableCommand.ExecuteReader();

我想做的是在datagrid中显示结果。.xaml部分如下所示:

  1. <DataGrid Name="myDataGrid" SelectionMode="Extended" SelectionUnit="Cell" AutoGenerateColumns="True" AlternatingRowBackground="LightCyan"
  2. ItemsSource="{Binding}" IsEnabled="True" IsReadOnly="True" Background="WhiteSmoke" Margin="13,27,8,110" CanUserSortColumns="True">
  3. </DataGrid>

.xaml.cs部分中用于将我的表的值显示到datagrid中的以下代码块完全是假设性的,只是为了澄清我想做什么:

  1. // suppose that I have read the list of headers (column names)
  2. // and suppose a button is clicked and an event is triggered and these codes are fit into that event
  3. List<string> myHeaders = new List<string>() { "ID" , "Name" , "Country" , "City" };
  4. myDataGrid.headers= myHeaders; // no method called "header" in reality
  5. While (myReader.Read())
  6. {
  7. myDataGrid.RowValues = myReader // no method called "RowValues" in reality
  8. }

我更喜欢没有单独类来管理datagrid的每一列的解决方案,因为这样很难有灵活的列数。显然我希望我的结果是这样的:

  1. ID | Name | Country | City
  2. ------------------------------------
  3. 123 | John | England | London
  4. ------------------------------------
  5. 456 | Jane | Ireland | Dublin
  6. ... ... ... ...

这个链接中没有一个答案有帮助:如何使用wpf在datagrid中显示sql搜索结果

arknldoa

arknldoa1#

解决方案:
多亏了“user1672994”,这个解决方案现在可以工作了:

  1. string mySQLQuery= "select * from myTable";
  2. SqlCommand myTableCommand = new SqlCommand(mySQLQuery, MyConnection);
  3. DataTable dt = new DataTable();
  4. SqlDataAdapter a = new SqlDataAdapter(myTableCommand );
  5. a.Fill(dt);
  6. myDataGrid.ItemsSource = dt.DefaultView;

相关问题