数据库
首页 > 数据库> > WPF显示SQLITE数据(四)--分页显示

WPF显示SQLITE数据(四)--分页显示

作者:互联网

  目前使用的WPF CORE做的BOSS网站数据显示,是在DataGrid中一次性显示数据,这样如果数据量大了,会对系统有一定压力,所以一般需要分页进行显示,显示中我参考了网上的一些已由控件,加入我的程序中,达到了分页效果。

  因为目前.net 5已经整合了.net core 3和.net Framework的功能,所以估计以后的趋势WPF也会都使用net core类库了,但是在开发使用中,发现目前的WPF CORE中无法添加WPF窗体和控件,经过多次试验,可以修改项目的.csproj文件,将<Project Sdk="Microsoft.NET.Sdk">改为<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">,然后直接添加一个已经写好的xaml分页控件(网上下载的,如果自己开发,又需要许多时间),控件代码如下:

       

 1 <UserControl x:Class="WpfApp1.DataGridPage"
 2              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
 5              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
 6              mc:Ignorable="d"  Background="Transparent">
 7     <UserControl.Resources>
 8         <!--每页{0}/共{0}条-->
 9         <Style x:Key="PageTextBlock1" TargetType="{x:Type TextBlock}">
10             <Setter Property="VerticalAlignment" Value="Center" />
11             <Setter Property="HorizontalAlignment" Value="Left" />
12             <Setter Property="FontSize" Value="13" />
13             <Setter Property="FontWeight" Value="Bold" />
14         </Style>
15         <!--首页上一页等-->
16         <Style x:Key="PageTextBlock2" TargetType="{x:Type TextBlock}">
17             <Setter Property="VerticalAlignment" Value="Center" />
18             <Setter Property="HorizontalAlignment" Value="Left" />
19             <Setter Property="Margin" Value="0,10,0,0" />
20             <Setter Property="Width" Value="40" />
21             <Setter Property="Height" Value="23" />
22             <Setter Property="FontSize" Value="13" />
23             <Setter Property="Cursor" Value="Hand" />
24             <Style.Triggers>
25                 <Trigger Property="IsMouseOver" Value="True">
26                     <Setter Property="Foreground" Value="#FF000000" />
27                     <Setter Property="FontWeight" Value="Bold" />
28                 </Trigger>
29             </Style.Triggers>
30         </Style>
31 
32     </UserControl.Resources>
33     <Grid>
34         <Border CornerRadius="3" Background="Transparent" BorderBrush="#01544A" BorderThickness="1">
35             <Grid HorizontalAlignment="Stretch" Margin="5 0 1 0" VerticalAlignment="Top" Width="Auto" Height="25">
36                 <Grid.ColumnDefinitions>
37                     <ColumnDefinition Width="100"/>
38                     <ColumnDefinition Width="300*" MinWidth="300"/>
39                 </Grid.ColumnDefinitions>
40                 <TextBlock Name="tbkRecords" Grid.Column="0" Style="{StaticResource PageTextBlock1}" Foreground="#01544A" Visibility="Visible" />
41                 <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="1">
42                     <Grid>
43                         <Grid.RowDefinitions >
44                             <RowDefinition Height="30"></RowDefinition>
45                         </Grid.RowDefinitions>
46                         <Grid.ColumnDefinitions>
47                             <ColumnDefinition Width="50"/>
48                             <ColumnDefinition Width="50"/>
49                             <ColumnDefinition Width="120*"/>
50                             <ColumnDefinition Width="50"/>
51                             <ColumnDefinition Width="30"/>
52                         </Grid.ColumnDefinitions>
53                         <TextBlock Grid.Column="0" Name="btnFirst" Text="  首页" IsEnabled="False" Style="{StaticResource PageTextBlock2}" MouseDown="btnFirst_MouseDown"/>
54                         <TextBlock Grid.Column="1" Name="btnPrev" Text="上一页" IsEnabled="False" Style="{StaticResource PageTextBlock2}" MouseDown="btnPrev_MouseDown" />
55                         <Grid Grid.Column="2" Name="grid" Visibility="Visible" >
56                             <TextBlock Text="第"    Style="{StaticResource PageTextBlock2}" Width="15" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="0"></TextBlock>
57                             <TextBox Width="30" Name="page" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20,0,0,0"></TextBox>
58                             <TextBlock HorizontalAlignment="Left" Width="60" VerticalAlignment="Bottom" Name="countPage" Text="页/共页"  Style="{StaticResource PageTextBlock2}" Margin="55,0,0,0"></TextBlock>
59                             <Button Name="btnGO" Content="GO"  Width="25" Height="20"  VerticalAlignment="Center" Margin="115,0,10,0" Click="btnGO_Click"></Button>
60                         </Grid>
61                         <TextBlock  Grid.Column="3" Name="btnNext" Text="下一页" IsEnabled="False" Style="{StaticResource PageTextBlock2}"  MouseDown="btnNext_MouseDown" Height="22" Margin="0,8,0,0"  />
62                         <TextBlock  Grid.Column="4" Name="btnLast" Text="末页" IsEnabled="False" Style="{StaticResource PageTextBlock2}" MouseDown="btnLast_MouseDown"/>
63                         
64                     </Grid>
65                 </StackPanel>
66             </Grid>
67         </Border>
68     </Grid>
69 </UserControl>

主窗体的调用代码为:

  1 using System.Data.SQLite;
  2 using System.IO;
  3 using System;
  4 using System.Windows;
  5 using System.Windows.Input;
  6 using System.Windows.Media;
  7 using System.Windows.Media.Imaging;
  8 using System.Windows.Navigation;
  9 using System.Windows.Shapes;
 10 using System.Windows.Controls;
 11 using System.Diagnostics;
 12 using System.Data;
 13 
 14 namespace WpfApp1
 15 {
 16     /// <summary>
 17     /// Interaction logic for MainWindow.xaml
 18     /// </summary>
 19     public partial class MainWindow : Window
 20     {
 21         public MainWindow()
 22         {
 23             InitializeComponent();
 24         }
 25 
 26         // 数据库文件夹
 27         static string DbPath = @"E:\mycsample\Boss\bin\x64\Debug\net5.0-windows";
 28         System.Data.DataTable Dt = new System.Data.DataTable();
 29 
 30         //与指定的数据库(实际上就是一个文件)建立连接
 31         private static SQLiteConnection CreateDatabaseConnection(string dbName = null)
 32         {
 33             if (!string.IsNullOrEmpty(DbPath) && !Directory.Exists(DbPath))
 34                 Directory.CreateDirectory(DbPath);
 35             dbName = dbName == null ? "mytest.db" : dbName;
 36             var dbFilePath = System.IO.Path.Combine(DbPath, dbName);
 37             return new SQLiteConnection("DataSource = " + dbFilePath+"; Pooling = true; FailIfMissing = false");
 38         }
 39 
 40         // 使用全局静态变量保存连接
 41         private static SQLiteConnection connection = CreateDatabaseConnection();
 42 
 43         // 判断连接是否处于打开状态
 44         private static void Open(SQLiteConnection connection)
 45         {
 46             if (connection.State != System.Data.ConnectionState.Open)
 47             {
 48                 connection.Open();
 49             }
 50         }
 51 
 52         public static void ExecuteNonQuery(string sql)
 53         {
 54             // 确保连接打开
 55             Open(connection);
 56             using (var tr = connection.BeginTransaction())
 57             {
 58                 using (var command = connection.CreateCommand())
 59                 {
 60                     command.CommandText = sql;
 61                     command.ExecuteNonQuery();
 62                 }
 63                 tr.Commit();
 64             }
 65         }
 66 
 67         public static SQLiteDataReader ExecuteQuery(string sql)
 68         {
 69             // 确保连接打开
 70             Open(connection);
 71             using (var tr = connection.BeginTransaction())
 72             {
 73                 using (var command = connection.CreateCommand())
 74                 {
 75                     command.CommandText = sql;
 76                     // 执行查询会返回一个SQLiteDataReader对象
 77                     var reader = command.ExecuteReader();
 78                     tr.Commit();
 79                     return reader;
 80                     //reader.Read()方法会从读出一行匹配的数据到reader中。注意:是一行数据。
 81                     //while (reader.Read())
 82                     //{
 83                     //    // 有一系列的Get方法,方法的参数是列数。意思是获取第n列的数据,转成Type返回。
 84                     //    // 比如这里的语句,意思就是:获取第0列的数据,转成int值返回。
 85                     //    var time = reader.GetInt64(0);
 86                     //}
 87                 }
 88                 //tr.Commit();
 89             }
 90         }
 91 
 92         private static void DeleteDatabase(string dbName)
 93         {
 94             var path = System.IO.Path.Combine(DbPath, dbName);
 95             connection.Close();
 96 
 97             // 置空,手动GC,并等待GC完成后执行文件删除。
 98             connection = null;
 99             GC.Collect();
100             GC.WaitForPendingFinalizers();
101             File.Delete(path);
102         }
103 
104         private void Hyperlink_Click(object sender, RoutedEventArgs e)
105         {
106             System.Windows.Documents.Hyperlink link = (System.Windows.Documents.Hyperlink)e.OriginalSource;
107             //Process.Start("IEXPLORE.EXE",link.NavigateUri.AbsoluteUri);
108             string url = link.NavigateUri.AbsoluteUri;
109             Process p = new Process();
110             p.StartInfo.FileName = "cmd.exe";
111             p.StartInfo.UseShellExecute = false;    //不使用shell启动
112             p.StartInfo.RedirectStandardInput = true;//喊cmd接受标准输入
113             p.StartInfo.RedirectStandardOutput = false;//不想听cmd讲话所以不要他输出
114             p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
115             p.StartInfo.CreateNoWindow = true;//不显示窗口
116             p.Start();
117 
118             //向cmd窗口发送输入信息 后面的&exit告诉cmd运行好之后就退出
119             p.StandardInput.WriteLine("start " + url + "&exit");
120             p.StandardInput.AutoFlush = true;
121             p.WaitForExit();//等待程序执行完退出进程
122             p.Close();
123         }
124 
125         private void button_Click(object sender, RoutedEventArgs e)
126         {
127             SQLiteDataReader sr = ExecuteQuery("select id,title,url from one_level order by id");
128             if (sr != null)
129             {                
130                 Dt.Load(sr);
131                 gridpage.ShowPages(dataGrid, Dt, 10);                
132                 //dataGrid.ItemsSource = Dt.DefaultView;
133             }
134         }
135 
136         private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
137         {
138             e.Row.Header = e.Row.GetIndex() + 1;
139         }
140 
141         private void dataGrid_UnLoadingRow(object sender, DataGridRowEventArgs e)
142         {
143             dataGrid_LoadingRow(sender, e);
144             if (dataGrid.Items != null)
145             {
146                 for (int i = 0; i < dataGrid.Items.Count; i++)
147                 {
148                     try
149                     {
150                         DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
151                         if (row != null)
152                         {
153                             row.Header = (i + 1).ToString();
154                         }
155                     }
156                     catch { }
157                 }
158             }
159         }
160 
161         private void Window_Loaded(object sender, RoutedEventArgs e)
162         {
163             //dataGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow);
164             //dataGrid.UnloadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_UnLoadingRow);
165         }
166     }
167 }

最后可以看到分页后的效果。

标签:SQLITE,--,System,private,dataGrid,Windows,connection,using,WPF
来源: https://www.cnblogs.com/djcsch2001/p/15451842.html