【问题标题】:UWP Application - Displaying data from SQL table onto Data Grid or ListboxUWP 应用程序 - 将 SQL 表中的数据显示到数据网格或列表框
【发布时间】:2021-09-30 04:06:21
【问题描述】:

我在将数据显示到数据网格甚至包含 SQL Server 表数据的列表框中时遇到了一些问题。 我能够使用 Windows 窗体应用程序而不是 UWP 在 DataGridView 中显示加载数据。如果这有什么不同,我将使用我在表单应用程序中使用的相同连接字符串。

在 Mainpage.xaml 我有这样的数据网格:

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

在 .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();

我读到将 itemSource 添加到网格视图时需要 DefaultView。 而不是在页面加载下,我还在按钮单击下实现了此代码以查看是否会显示任何数据,但我得到:System.Data.SqlClient.SqlException:'建立连接时发生与网络相关或特定于实例的错误到 SQL Server。服务器未找到或无法访问错误。

想知道什么是解决此问题的最佳方法,以及如何显示我的 SQL Server 表中的信息。谢谢。

【问题讨论】:

    标签: c# wpf windows visual-studio uwp


    【解决方案1】:

    要从SQL Server数据库中检索数据并在DataGrid中显示,首先需要创建一个类,其属性对应数据表的列名,然后使用SqlDataReader.Read()方法读取每一行的数据并转换每个记录到一个类对象,最后将它们写入一个集合。请参考以下代码。

      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; }
    }
    

    更多信息可以在这里找到。Retrieve products from the SQL Server database

    【讨论】:

    • 感谢您对此进行调查,终于有时间尝试进行故障排除。我尝试采纳您的建议,并查看了 Microsoft 文档。当我运行应用程序时,只有表格的标题显示在 DataGrid 中,但没有数据行。我不太清楚为什么会这样。
    • 我尝试再次重新创建应用程序,但只有我的 SQL 表的标题显示没有数据显示。看起来它只是根据我的 DataInfo 类方法(字符串、日期时间)填充标题。 100% 确定我也有数据行。
    • 数据绑定的过程好像有问题。你需要注意我在 SQL 数据库中有一个表,它有两列名为 NameTime,它们的类型是(nchar(10))Date。因此,我创建了一个 DataInfo 类,其中有两个指定的属性与表对应,并使用reader.GetString(0)reader.GetDateTime(1) 来获取第一、第二列数据。这意味着如果表中有 Int32 类型的列,则需要使用 reader.GetInt32(ColumnIndex) 获取数据并在 DataInfo 类中添加具有 Int 类型的属性。跨度>
    • 关键是创建一个正确的类对应表,并使用合适的SqlDataReader方法获取每一列的数据。如果您按照上述操作,那么您可以检查 results 集合是否有数据。
    • 我在控制台应用程序上使用相同的连接详细信息,但对于 UWP,我收到了这些错误。这是我在调试控制台上得到的: 异常抛出:System.Data.SqlClient.dll 中的“System.Data.SqlClient.SqlException”异常:建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:TCP 提供者,错误:40 - 无法打开与 SQL Server 的连接)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2020-12-15
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多