【问题标题】:Show the result of a SQL query in a DataGrid in WPF App在 WPF 应用程序的 DataGrid 中显示 SQL 查询的结果
【发布时间】:2020-11-25 13:34:42
【问题描述】:

查询的结果在 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

【问题讨论】:

  • 尝试使用DataTable 添加行和列,然后将数据表分配为网格的ItemsSource 属性。在这种情况下,在 XAML 中您不需要 ItemsSource="{Binding}
  • @user1672994 谢谢。似乎是一个很好的解决方案,但我得到了一些奇怪的结果;包含此列的表:“RowError, RowState, Table, ItemArray, HasErrors”。为了将 DataTable 分配给我的 myDataGrid.ItemsSource,我必须首先将 DataTable 转换为 IEnumerable。所以我这样做了:myDataGrid.ItemsSource = myDataTable.AsEnumerable(); 没有错误,但正如我所说,奇怪的结果。

标签: c# sql wpf xaml datagrid


【解决方案1】:

解决方案

感谢“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;

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2017-10-17
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多