一、實驗目的
- 掌握ADO .NET數據離線與在線訪問模型;
- 掌握應用LINQ進行數據查詢;
- 繼續應用WPF技術進行界面編程。
二、實驗內容
使用提供的Northwind.mdb數據庫,利用DataGrid控件進行數據庫查詢與更新:
1、新建WPF工程與窗口。
2、添加“選擇查詢條件”標籤,再加一個ComboBox,設置其元素包含“客戶”表的主要字段名(公司名稱、聯繫人姓名、城市)。
3、添加“設置查詢值”標籤,再加一個Combobox,供輸入查詢用的值;添加“開始查詢”按鈕;添加一個DataGrid控件。
4、定義GetAllGuests()方法,獲取數據,放入DataGrid控件的ItemsSource字段。在窗體裝載(Load)時調用它,作爲DataGrid控件的數據源,展示“客戶”表中所有信息。
5、定義GetAllColumns方法,獲取某列中數據。在用戶選擇查詢條件後,調用該方法,將所得數據作爲“查詢值Combobox”的數據源。獲取列名的方法:
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
List<string> columns = new List<string>();
for(int i=0; i<reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
comboColumn.ItemsSource = columns;
6、定義DataView GetSelectedGuest()方法。點擊查詢按鈕後,將查詢所得數據展現出來。
7、在下方添加一個標籤控件,在點擊DataGrid控件中某行時,響應CellClick事件。查詢“訂單”表,在標籤控件中顯示“xx客戶共有xx個訂單”信息。
獲取客戶ID:
DataRowView data = gridData.SelectedItem as DataRowView;
if (data == null)
return;
string id = data["客戶ID"].ToString();
8*、可以根據自己的想法,添加更加豐富的功能。比如引入圖表控件(livecharts等),將查詢到的數據展示在圖表中。
源代碼
XAML
<Window x:Class="Homework13.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
xmlns:local="clr-namespace:Homework13"
mc:Ignorable="d"
Title="簡易數據庫查詢工具" Height="450" Width="1294.239" Loaded="Window_Loaded">
<Grid>
<Grid Margin="0,0,0,0">
<Button Content="全部" HorizontalAlignment="Left" Margin="10,15,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
<Label Content="選擇查詢條件:" HorizontalAlignment="Left" Margin="100,15,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="comboColumn" HorizontalAlignment="Left" Margin="200,15,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="comboColumn_SelectionChanged"/>
<Label Content="設置查詢值:" HorizontalAlignment="Left" Margin="350,15,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="comboRow" HorizontalAlignment="Left" Margin="450,15,0,0" VerticalAlignment="Top" Width="120"/>
<Button Content="查詢" HorizontalAlignment="Left" Margin="600,15,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<DataGrid x:Name="datagrid" HorizontalAlignment="Left" Height="325" Margin="0,50,0,0" VerticalAlignment="Top" Width="800" MouseUp="datagrid_MouseUp"/>
<Label x:Name="status" Content="" HorizontalAlignment="Left" Margin="0,375,0,0" VerticalAlignment="Top" Height="25" Width="800"/>
</Grid>
<lvc:PieChart x:Name="chart" LegendLocation="Bottom" DataClick="Chart_OnDataClick" Hoverable="False" DataTooltip="{x:Null}" Height="325" Margin="800,0,0,0" >
<lvc:PieChart.Series>
<!--DataLabels屬性是顯示模塊標籤的、PointLabel是佔比-->
<lvc:PieSeries Title="Maria" Values="3" DataLabels="True"
LabelPoint="{Binding PointLabel}"/>
<lvc:PieSeries Title="Charles" Values="4" DataLabels="True"
LabelPoint="{Binding PointLabel}"/>
<lvc:PieSeries Title="Frida" Values="6" DataLabels="True"
LabelPoint="{Binding PointLabel}"/>
<lvc:PieSeries Title="Frederic" Values="2" DataLabels="True"
LabelPoint="{Binding PointLabel}"/>
</lvc:PieChart.Series>
</lvc:PieChart>
</Grid>
</Window>
CS
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LiveCharts;
using LiveCharts.Wpf;
namespace Homework13
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
static string _mdbFile = "E:\\School Life\\University\\Study\\計算機\\程序語言\\C#\\第十三次課0529\\Northwind\\Northwind.mdb";
static OleDbConnection _connection;
static OleDbDataAdapter _adapter;
static DataSet _dataset;
// 使用泛型動態傳入數據
public Func<ChartPoint, string> PointLabel { get; set; }
public MainWindow()
{
InitializeComponent();
// 自定義顯示標籤
PointLabel = chartPoint =>
string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation);
DataContext = this;
}
public void GetAllGuests()
{
DataView dataView = GetSelectedGuest();
datagrid.ItemsSource = dataView;
SeriesCollection series = new SeriesCollection();
Dictionary<String, int> d = new Dictionary<string, int>();
foreach (DataRow row in dataView.Table.Rows) {
if (!d.ContainsKey(row.Field<string>("地區")))
{
//已存在key
d.Add(row.Field<string>("地區"),0);
}
d[row.Field<string>("地區")]++;
}
foreach (var pair in d) {
series.Add(new PieSeries
{
Title = pair.Key,
Values = new ChartValues<int> { pair.Value },
DataLabels = true,
LabelPoint = PointLabel
}) ;
}
chart.Series = series;
}
public void GetAllColumns()
{
var command = _connection.CreateCommand();
command.CommandText = "select * from 客戶";
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
List<string> columns = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
comboColumn.ItemsSource = columns;
reader.Close();
}
public DataView GetSelectedGuest()
{
var command = _connection.CreateCommand();
command.CommandText = "select * from 客戶";
Console.WriteLine(status.Content);
if (comboColumn.SelectedIndex != -1 && comboRow.SelectedIndex != -1)
{
command.CommandText = "select * from 客戶 where " + comboColumn.Text + "='" + comboRow.Text + "'";
}
status.Content = command.CommandText;
_dataset = new DataSet();
DataTable dt1 = new DataTable("Scene");
_dataset.Tables.Add(dt1);
_adapter = new OleDbDataAdapter(command);
_adapter.Fill(dt1);
return dt1.DefaultView;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + _mdbFile;
_connection = new OleDbConnection(connString);
//補全
try
{
_connection.Open();
Console.WriteLine("數據庫連接成功:" + _mdbFile + " is " + _connection.State);
GetAllGuests();
GetAllColumns();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
_connection.Close();
}
finally
{
}
}
private void comboColumn_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (comboColumn.SelectedIndex == -1) {
comboRow.ItemsSource = null;
return;
}
var command = _connection.CreateCommand();
command.CommandText = "select * from 客戶";
OleDbDataReader reader = command.ExecuteReader();
SortedSet<string> columns = new SortedSet<string>();
while(reader.Read())
{
columns.Add(reader[comboColumn.SelectedIndex].ToString());
}
comboRow.ItemsSource = columns;
reader.Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
GetAllGuests();
}
private void datagrid_MouseUp(object sender, MouseButtonEventArgs e)
{
DataRowView data = datagrid.SelectedItem as DataRowView;
if (data == null)
return;
string id = data["客戶ID"].ToString();
var command = _connection.CreateCommand();
command.CommandText = "select count(*) from 訂單 where 客戶ID='"+ id +"'";
int count = (int)command.ExecuteScalar();
status.Content = data["客戶ID"]+"客戶共有" + count + "個訂單";
Console.WriteLine("記錄總數:" + count);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
comboColumn.SelectedIndex = -1;
GetAllGuests();
}
/**
* 餅圖鼠標點擊事件
*/
private void Chart_OnDataClick(object sender, ChartPoint chartpoint)
{
var chart = (LiveCharts.Wpf.PieChart)chartpoint.ChartView;
//clear selected slice.
foreach (PieSeries series in chart.Series)
series.PushOut = 0;
var selectedSeries = (PieSeries)chartpoint.SeriesView;
selectedSeries.PushOut = 8;
}
}
}
運行結果
三、實驗心得與體會
- 掌握ADO .NET數據離線與在線訪問模型;
- 掌握應用LINQ進行數據查詢;
- 繼續應用WPF技術進行界面編程。
參考文章
https://blog.csdn.net/zdyueguanyun/article/details/51392477
https://blog.csdn.net/sinat_33607851/article/details/50451255
https://www.cnblogs.com/wleaves/p/4689250.html
https://blog.csdn.net/CalledJoker/article/details/89356164