简体   繁体   English

UWP 应用程序 - 将 SQL 表中的数据显示到数据网格或列表框上

[英]UWP Application - Displaying data from SQL table onto Data Grid or Listbox

I am having some trouble displaying data onto a data grid or even a list box with data from an SQL Server table.我在将数据显示到数据网格或什至包含来自 SQL Server 表的数据的列表框中时遇到了一些问题。 I was able to do display the data on load in a DataGridView with a Windows Forms App but not with UWP.我能够使用 Windows 窗体应用程序在 DataGridView 中显示加载时的数据,但不能使用 UWP。 I am using the same connection string that I used in my Form App if that makes any difference.如果有任何区别,我使用的连接字符串与我在表单应用程序中使用的连接字符串相同。

In the Mainpage.xaml I have the datagrid as this:在 Mainpage.xaml 我有这样的数据网格:

<Custom:DataGrid x:Name="dataGridView1" ItemsSource="{Binding}"/> 
 <ListBox x:Name="lbData" ItemsSource="{Binding}" Margin="803,428,386,434"/>

In .cs page:在 .cs 页面中:

 SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Server=(local);Database=databaseName;" + "User=someuser; Password=somepassword";
    
SqlCommand cmd = conn.CreateCommand();

string query = "Select * FROM TABLE_NAME";
                cmd.CommandText = query;
                conn.Open();

                SqlDataReader reader = cmd.ExecuteReader();
                reader.Read();

                DataTable dt = new DataTable();
                dt.Load(reader);



                dataGridView1.ItemsSource = dt.DefaultView;
                lbData.ItemsSource = dt.DefaultView;
                dataGridView1.AutoGenerateColumns = true;

                reader.Close();

                cmd.Dispose();
                conn.Close();

I read that DefaultView is required when adding an itemSource to a grid view.我读到将 itemSource 添加到网格视图时需要 DefaultView 。 Instead of under page loaded, I also implemented this code under a button click to see if any data would show but I got a: System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server.而不是在页面加载下,我还在按钮单击下实现了此代码以查看是否会显示任何数据,但我得到了一个:System.Data.SqlClient.SqlException:'建立连接时发生了与网络相关或特定于实例的错误到 SQL Server。 The server was not found or was not accessible error.服务器未找到或无法访问错误。

Wondering what would be the best fix for this and how I would be able to display the information from my SQL Server table.想知道什么是最好的解决方法,以及我如何能够显示我的 SQL Server 表中的信息。 Thanks.谢谢。

To retrieve data from the SQL Server database and show it in DataGrid, first you need to create a class whose properties corresponding to the column name of the data table, then use SqlDataReader.Read() method to read data for each row and convert each record to a class object, finally write them to a collection.从 SQL Server 数据库中检索数据并在 DataGrid 中显示,首先需要创建一个类,其属性与数据表的列名对应,然后使用SqlDataReader.Read()方法读取每一行的数据并转换每个记录到类对象,最后将它们写入集合。 Please refer to the following code.请参考以下代码。

  public sealed partial class MainPage : Page
    {
        public ObservableCollection<DataInfo> results;
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            results = new ObservableCollection<DataInfo>();
            string ConnectionString = "Data Source =xx;Initial Catalog =xx;User ID=xx;Password=xx";
            string query = "Select * FROM timedemo1";
            try
            {
                using(SqlConnection conn=new SqlConnection(ConnectionString))
                {
                    conn.Open();
                    if (conn.State == ConnectionState.Open)
                    {
                        using(SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = query;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {

                                while (reader.Read())
                                {
                                    DataInfo data = new DataInfo();
                                    data.name = reader.GetString(0);  //first column datatype:(nchar(10))
                                    data.time = reader.GetDateTime(1); //second column datatype:(date)
                                    results.Add(data);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception:"+ ex.Message);
            }           
          myDataGrid.ItemsSource =results;       
          myDataGrid.AutoGenerateColumns = true;    
        }
      
    }

    public class DataInfo
    {
        public string name { get; set; }
        public DateTime time { get; set; }
}

More info could be found here.更多信息可以在这里找到。 Retrieve products from the SQL Server database 从 SQL Server 数据库中检索产品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM