先上效果圖:
XAML:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfAppFirst" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:dxprg="http://schemas.devexpress.com/winfx/2008/xaml/propertygrid" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" x:Class="WpfAppFirst.CheckList" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="1000"> <Grid> <!--#region 網線--> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="40*"/> <RowDefinition Height="60*"/> <RowDefinition Height="140*"/> <RowDefinition Height="60*"/> </Grid.RowDefinitions> <!--#endregion--> <!--#region 標題--> <Border Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="4" Grid.RowSpan="1"> <Label Content="核查單位管理" Foreground="#000" FontSize="24" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> <!--#endregion--> <!--#region 單位名稱--> <Label Content="單位名稱" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" VerticalContentAlignment="Center" FontSize="18"></Label> <TextBox x:Name="Users_Company" Width="120" Height="30" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,10,0"></TextBox> <!--#endregion--> <!--#region 負責人--> <Label Content="負責人" Grid.Column="2" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" VerticalContentAlignment="Center" FontSize="18"></Label> <TextBox x:Name="Users_Name" Width="120" Height="30" Grid.Column="2" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,10,0"></TextBox> <!--#endregion--> <!--#region 狀態--> <Label Content="狀態" Grid.Column="3" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" VerticalContentAlignment="Center" Padding="50,0,0,0" FontSize="18"></Label> <ComboBox x:Name="Users_IsDelete" Width="80" Height="30" Grid.Column="3" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,10,0"> <ComboBoxItem IsSelected="True">全部</ComboBoxItem> <ComboBoxItem>有效</ComboBoxItem> <ComboBoxItem>無效</ComboBoxItem> </ComboBox> <!--#endregion--> <!--#region 查詢 添加--> <Border Grid.Column="4" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" Background="#2862AD" Height="30" Width="65" CornerRadius="2,2,2,2" HorizontalAlignment="Left" MouseLeftButtonDown="Border_MouseLeftButtonDown" Cursor="Hand"> <Label Content="查詢" FontSize="18" Foreground="#fff" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> <Border Grid.Column="4" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" Background="#2862AD" Height="30" Width="65" CornerRadius="2,2,2,2" HorizontalAlignment="Right" MouseLeftButtonDown="Border_MouseLeftButtonDown_1" Cursor="Hand"> <Label Content="添加" FontSize="18" Foreground="#fff" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> <!--<Border Grid.Column="4" Grid.Row="1" Grid.ColumnSpan="1" Grid.RowSpan="1" Background="Red" ></Border>--> <!--#endregion--> <!--#region 表格--> <DataGrid x:Name="dataGrid1" Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="4" CanUserAddRows="False" AutoGenerateColumns="False" SelectionUnit="FullRow" ColumnHeaderHeight="40" Background="Transparent" SelectionMode="Single"> <!--數據網格的樣式屬性--> <DataGrid.Style> <!--DataGrid樣式--> <Style TargetType="DataGrid"> <!--設置HeadersVisibility:頭部可見性,Column--> <Setter Property="HeadersVisibility" Value="Column"/> <!--水平網格線刷能見度--> <Setter Property="HorizontalGridLinesBrush"> <Setter.Value> <SolidColorBrush Color="#333" Opacity="0.2"/> </Setter.Value> </Setter> <!--垂直網格線刷--> <Setter Property="VerticalGridLinesBrush"> <Setter.Value> <SolidColorBrush Color="#333" Opacity="0.2"/> <!--Transparent--> </Setter.Value> </Setter> </Style> </DataGrid.Style> <!--數據網格的列標題樣式屬性--> <DataGrid.ColumnHeaderStyle> <!--樣式類型:DataGridColumnHeader(數據網格列標題)--> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="Background" Value="#E1F1FF"/> <Setter Property="Foreground" Value="#000"/> <Setter Property="HorizontalContentAlignment" Value="Center"/> <!--設置邊框筆刷(BorderBrush)--> <Setter Property="BorderBrush"> <!--值--> <Setter.Value> <!--色刷,Opacity:透明度--> <SolidColorBrush Color="#333" Opacity="0.2"></SolidColorBrush> </Setter.Value> </Setter> </Style> </DataGrid.ColumnHeaderStyle> <!--DataGrid的Rowstyle屬性(數據表格的行樣式)--> <DataGrid.RowStyle> <!--設置樣式,類型:DataGridRow(數據表格行)--> <Style TargetType="DataGridRow"> <!--設置BorderThickness:邊框粗細,value:值0--> <Setter Property="BorderThickness" Value="0"/> <!--<Setter Property="Background" Value="Transparent"/>Transparent:透明--> <!--創建樣式觸發器--> <Style.Triggers> <!--是否是鼠標經過觸發--> <Trigger Property="IsMouseOver" Value="True"> <!--觸發:背景顏色--> <Setter Property="Background"> <!--Color:背景顏色值;Opacity:透明度--> <Setter.Value> <SolidColorBrush Color="#E1F1FF" Opacity="1"></SolidColorBrush> </Setter.Value> </Setter> </Trigger> <!--是否選中時觸發--> <Trigger Property="IsSelected" Value="True"> <!--觸發:Foreground(字體顏色);Value:顏色值:Red--> <Setter Property="Foreground" Value="Red"/> </Trigger> </Style.Triggers> </Style> </DataGrid.RowStyle> <!--DataGrid的CellStyle屬性(數據表格的單元格樣式)--> <DataGrid.CellStyle > <!--設置樣式,類型:DataGridCell(數據表格的單元格)--> <Style TargetType="DataGridCell"> <!--設置BorderThickness:邊框粗細,value:值0--> <Setter Property="BorderThickness" Value="0"/> <!--樣式的觸發器--> <Style.Triggers> <!--是否選中是觸發--> <Trigger Property="IsSelected" Value="True"> <!--觸發:背景--> <Setter Property="Background"> <!--設置觸發背景的值--> <Setter.Value> <!--Color:顏色,Opacity:透明度--> <SolidColorBrush Color="AntiqueWhite" Opacity="0.9"/> </Setter.Value> </Setter> <!--設置字體顏色(Foreground):紅色(Red)--> <Setter Property="Foreground" Value="Red"></Setter> </Trigger> </Style.Triggers> </Style> </DataGrid.CellStyle> <DataGrid.Columns> <!--用這種的話,單元格不能放多個可點擊的控件,這個可以:DataGridTemplateColumn--> <!--<DataGridTextColumn Header="單位" Width="*" Binding="{Binding Company}" IsReadOnly="True"> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="HorizontalAlignment" Value="Center"></Setter> <Setter Property="FontSize" Value="14" /> <Setter Property="FontFamily" Value="微軟雅黑" /> <Setter Property="Height" Value="40" /> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn>--> <!--數據表格模板列;Header:標題,Width:{比例(*),固定值(int)}--> <DataGridTemplateColumn Header="編號" Width="*"> <!--數據表格模板列的單元格模板屬性--> <DataGridTemplateColumn.CellTemplate> <!--數據模板--> <DataTemplate> <!--堆疊盤--> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock Text="{Binding Id}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="負責人" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock Text="{Binding Name}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="單位" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock Text="{Binding Company}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="狀態" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock Text="{Binding IsDelete}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="操作" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Height="40"> <!--框--> <Border x:Name="borderEdit" HorizontalAlignment="Center" VerticalAlignment="Center" MouseLeftButtonDown="s_MouseLeftButtonDown"> <Label Content="編輯" FontSize="14" VerticalAlignment="Center" Cursor="Hand"></Label> </Border> <Border x:Name="borderDelete" HorizontalAlignment="Center" VerticalAlignment="Center" MouseLeftButtonDown="Label_MouseDoubleClick" Cursor="Hand"> <Label Content="刪除" FontSize="14" VerticalAlignment="Center"></Label> </Border> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> <!--<DataGridTemplateColumn.CellTemplate> <DataTemplate> <Label Content="修改" MouseDoubleClick="s_MouseLeftButtonDown" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"></Label> </DataTemplate> </DataGridTemplateColumn.CellTemplate>--> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <!--#endregion--> <!--#region 總記錄數據--> <Border Grid.Column="1" Grid.Row="3"> <Label x:Name="count" FontSize="16" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> <!--#endregion--> <!--#region 轉到第幾頁--> <Border Grid.Column="4" Grid.Row="3"> <Label Content="轉到 頁" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Padding="0,0,15,0"></Label> </Border> <Border Grid.Column="4" Grid.Row="3"> <TextBox x:Name="Page" Width="30" Height="20" InputMethod.IsInputMethodEnabled="False" PreviewTextInput="Page_PreviewTextInput"></TextBox> </Border> <Border Grid.Column="4" Grid.Row="3" VerticalAlignment="Center" HorizontalAlignment="Right"> <Button Content="確定" Width="60" Height="20" VerticalContentAlignment="Center" Click="Button_Click"></Button> </Border> <!--#endregion--> <!--#region 上一頁--> <Border Grid.Column="3" Grid.Row="3"> <Image Source="Img\右2.png" Width="20" Height="20" VerticalAlignment="Center" HorizontalAlignment="Left" Cursor="Hand" MouseUp="Image_MouseUp"></Image> </Border> <Border Grid.Column="3" Grid.Row="3"> <Image Source="Img\右1.png" Width="20" Height="20" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="20,0,0,0" Cursor="Hand" MouseUp="Image_MouseUp_1"></Image> </Border> <!--#endregion--> <!--#region 頁數--> <Border Grid.Column="3" Grid.Row="3"> <Label x:Name="CurrentPage" Content="1" Foreground="Red" FontSize="12" Width="30" Height="30" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="0,0,100,0" Cursor="Hand"></Label> </Border> <Border Grid.Column="3" Grid.Row="3"> <Label x:Name="CurrentPage2" Content="1" FontSize="12" Width="30" Height="30" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="0,0,70,0" Cursor="Hand"></Label> </Border> <Border Grid.Column="3" Grid.Row="3"> <Label x:Name="CurrentPage3" Content="1" FontSize="12" Width="30" Height="30" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="0,0,40,0" Cursor="Hand"></Label> </Border> <Border Grid.Column="3" Grid.Row="3"> <Label Content="...." FontSize="12" Width="20" Height="30" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Cursor="Hand"></Label> </Border> <Border Grid.Column="3" Grid.Row="3"> <Label x:Name="MaxPage" FontSize="12" Width="30" Height="30" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="50,0,0,0" Cursor="Hand"></Label> </Border> <!--#endregion--> <!--#region 下一頁--> <Border Grid.Column="3" Grid.Row="3"> <Image Source="Img\左1.png" Width="20" Height="20" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,20,0" Cursor="Hand" MouseUp="Image_MouseUp_3"></Image> </Border> <Border Grid.Column="3" Grid.Row="3"> <Image Source="Img\左2.png" Width="20" Height="20" VerticalAlignment="Center" HorizontalAlignment="Right" Cursor="Hand" MouseUp="Image_MouseUp_2"></Image> </Border> <!--#endregion--> </Grid> </UserControl>
后台隱藏代碼:
using ExerciseModel; using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; using System.Text.RegularExpressions; 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; namespace WpfAppFirst { /// <summary> /// CheckList.xaml 的交互邏輯 /// </summary> public partial class CheckList : UserControl { /// <summary> /// 當前頁數 /// </summary> private int Currentpage = 1; /// <summary> /// 每頁數據行 /// </summary> private int pageRecord = 2; /// <summary> /// 構造函數 /// </summary> public CheckList() { InitializeComponent(); this.count.Content = "共" + conns().Count() + "條數據"; SetCurrentPage(Currentpage.ToString()); this.MaxPage.Content = MaxPaging(); this.Page.Text = Currentpage.ToString(); } #region 連接數據庫 OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\用戶目錄\\我的文檔\\Access\\Organization.mdb"); //Jet OLEDB:Database Password= #endregion #region 事件 /// <summary> /// 修改 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void s_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { GetSelectedRow(); UpdateUser uu = new WpfAppFirst.UpdateUser(); uu.Ids.Content = SubRowsId().Id; uu.ShowDialog(); Paging(pageRecord, Currentpage); //UpdateUser(SubRowsId().Name, SubRowsId().Company, SubRowsId().IsDelete, SubRowsId().Id); } /// <summary> /// 點擊刪除 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e) { MessageBoxResult result = MessageBox.Show("請確認刪除此條數據?", "", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { DeleteUser(SubRowsId().Id); Paging(pageRecord, Currentpage); this.MaxPage.Content = MaxPaging(); this.Page.Text = MaxPaging().ToString(); this.count.Content = conns().Count(); } } /// <summary> /// 條件查詢 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { SeleteWhere(GetName(), GetCompany(), GetIsDelete()); } /// <summary> /// 添加 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Border_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e) { AddUser(GetName(), GetCompany(), GetIsDelete()); int max = Convert.ToInt32(MaxPaging()); Paging(pageRecord, max); Currentpage = max; this.MaxPage.Content = MaxPaging(); this.Page.Text = MaxPaging().ToString(); this.count.Content = conns().Count(); } /// <summary> /// 跳轉頁數 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click(object sender, RoutedEventArgs e) { var page = this.Page.Text; var maxpage = MaxPaging(); if (Convert.ToDouble(page) > maxpage) { Paging(pageRecord, Convert.ToInt32(maxpage)); SetCurrentPage(maxpage.ToString()); Currentpage = Convert.ToInt32(maxpage); Setpage(maxpage.ToString()); } if (Convert.ToDouble(page) < 0) { Paging(pageRecord, 1); SetCurrentPage("1"); Currentpage = 1; Setpage("1"); } else if (Convert.ToDouble(page) <= maxpage && Convert.ToDouble(page) > 0) { Paging(pageRecord, Convert.ToInt32(page)); SetCurrentPage(page); Currentpage = Convert.ToInt32(page); Setpage(page); } } /// <summary> /// 利用正則表達式禁用英文的寫入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex re = new Regex("[^0-9.-]+"); e.Handled = re.IsMatch(e.Text); } /// <summary> /// 第一頁 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Image_MouseUp(object sender, MouseButtonEventArgs e) { if (Currentpage != 1) { Setpage("1"); SetCurrentPage("1"); Paging(pageRecord, 1); Currentpage = 1; } } /// <summary> /// 上一頁 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Image_MouseUp_1(object sender, MouseButtonEventArgs e) { if (Currentpage != 1) { Setpage((Currentpage - 1).ToString()); SetCurrentPage((Currentpage - 1).ToString()); Paging(pageRecord, --Currentpage); } } /// <summary> /// 最后一頁 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Image_MouseUp_2(object sender, MouseButtonEventArgs e) { double MaxPage = MaxPaging(); if (Currentpage != MaxPage) { Setpage(MaxPage.ToString()); SetCurrentPage(MaxPage.ToString()); Paging(pageRecord, (int)MaxPage); Currentpage = (int)MaxPage; } } /// <summary> /// 下一頁 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Image_MouseUp_3(object sender, MouseButtonEventArgs e) { double MaxPage = MaxPaging(); if (Currentpage != MaxPage) { Setpage((Currentpage + 1).ToString()); SetCurrentPage((Currentpage + 1).ToString()); Paging(pageRecord, ++Currentpage); } } #endregion #region 方法 private DataRowView GetSelectedRow() { /*優化 * 無論 DataGrid的SelectionUnit跟SelectionMode兩個屬性取任何值 * 都存在選中的單元格 * 可以根據選中的單元格做統一處理,獲取選中的行 * GetSelectedRows()方法獲取選中多行原理相同 */ if (dataGrid1 != null && dataGrid1.SelectedCells.Count != 0) { //只選中一個單元格時:返回單元格所在行 //選中多個時:返回第一個單元格所在行 return dataGrid1.SelectedCells[0].Item as DataRowView; } return null; } #region 連接開關 public void ConnOpen() { if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } } public void ConnClose() { if (conn.State == System.Data.ConnectionState.Open) { conn.Close(); } } #endregion #region 設置當前頁 /// <summary> /// 設置當前頁 /// </summary> /// <param name="page">當前頁數</param> public void SetCurrentPage(string page) { this.CurrentPage.Content = page; int max = Convert.ToInt32(MaxPaging()); if (Convert.ToInt32(page) <= max - 1) { this.CurrentPage2.Content = Convert.ToInt32(page) + 1; } else { this.CurrentPage2.Content = ""; } if (Convert.ToInt32(page) <= max - 2) { this.CurrentPage3.Content = Convert.ToInt32(page) + 2; } else { this.CurrentPage3.Content = ""; } } /// <summary> /// 設置文本框中的當前數值 /// </summary> /// <param name="page"></param> public void Setpage(string page) { this.Page.Text = page; } #endregion #region 最大頁 /// <summary> /// 獲取最大頁 /// </summary> /// <returns></returns> public double MaxPaging() { double count = conns().Count(); return Math.Ceiling(count / pageRecord); } #endregion #region 獲取選中行的原始值 /// <summary> /// 獲取選中行的原始值 /// </summary> /// <param name="rowindex"></param> private Users1 SubRowsId() { return (Users1)dataGrid1.SelectedItem; } #endregion #region 獲取文本 /// <summary> /// 獲取負責人 /// </summary> public string GetName() { return this.Users_Name.Text; } /// <summary> /// 獲取負責人單位 /// </summary> /// <returns></returns> public string GetCompany() { return this.Users_Company.Text; } /// <summary> /// 獲取狀態值 /// </summary> /// <returns></returns> public bool? GetIsDelete() { var bl = this.Users_IsDelete.Text.ToString(); if (bl == "全部") { return null; } else if (bl == "有效") { return true; } else { return false; } } #endregion #region 查詢全部數據 /// <summary> /// 查詢全部數據 /// </summary> public List<Users1> conns() { OleDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from Users"; ConnOpen(); OleDbDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); if (dr.HasRows) { for (int i = 0; i < dr.FieldCount; i++) { dt.Columns.Add(dr.GetName(i)); } dt.Rows.Clear(); } while (dr.Read()) { DataRow row = dt.NewRow(); for (int i = 0; i < dr.FieldCount; i++) { row[i] = dr[i]; } dt.Rows.Add(row); } cmd.Dispose(); ConnClose(); List<Users1> lus1 = new List<Users1>(); for (int i = 0; i < dt.Rows.Count; i++) { lus1.Add(new Users1 { Id = Convert.ToInt32(dt.Rows[i][0]), Name = dt.Rows[i][1].ToString(), Company = dt.Rows[i][2].ToString(), IsDelete = Convert.ToBoolean(dt.Rows[i][3]) }); } return lus1; //this.dataGrid1.ItemsSource = lus1; } #endregion #region 分頁 /// <summary> /// /// </summary> /// <param name="pageSize">頁大小</param> /// <param name="currentPage">當前頁數</param> /// <param name="totalCount">總頁數</param> public void Paging(int pageSize, int currentPage) { //pageSize 每頁顯示多少條數據 //pageNumber 頁數 從客戶端傳來 //pages = pageSize * (currentPage - 1) + 1 int pages = pageSize * (currentPage - 1) + 1; string sql = string.Format("select top {0} * from Users where id>=(select max(id) from (select top {1} id from Users order by id asc ) t )", pageSize, pages); OleDbCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; ConnOpen(); OleDbDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); if (dr.HasRows) { for (int i = 0; i < dr.FieldCount; i++) { dt.Columns.Add(dr.GetName(i)); } dt.Rows.Clear(); } while (dr.Read()) { DataRow row = dt.NewRow(); for (int i = 0; i < dr.FieldCount; i++) { row[i] = dr[i]; } dt.Rows.Add(row); } cmd.Dispose(); ConnClose(); List<Users1> lus1 = new List<Users1>(); for (int i = 0; i < dt.Rows.Count; i++) { lus1.Add(new Users1 { Id = Convert.ToInt32(dt.Rows[i][0]), Name = dt.Rows[i][1].ToString(), Company = dt.Rows[i][2].ToString(), IsDelete = Convert.ToBoolean(dt.Rows[i][3]) }); } this.dataGrid1.ItemsSource = lus1; } #endregion #region 條件查詢 private void SeleteWhere(string Name, string Company, bool? IsDelete) { OleDbCommand cmd = conn.CreateCommand(); string sql1 = string.Format("select * from Users where Name='{0}' or Company='{1}' and IsDelete={2}", Name, Company, IsDelete); string sql2 = string.Format("select * from Users where Name='{0}' or Company='{1}'", Name, Company); if (IsDelete != null) { cmd.CommandText = sql1; } else { cmd.CommandText = sql2; } ConnOpen(); OleDbDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); if (dr.HasRows) { for (int i = 0; i < dr.FieldCount; i++) { dt.Columns.Add(dr.GetName(i)); } dt.Rows.Clear(); } while (dr.Read()) { DataRow row = dt.NewRow(); for (int i = 0; i < dr.FieldCount; i++) { row[i] = dr[i]; } dt.Rows.Add(row); } cmd.Dispose(); ConnClose(); List<Users1> lus1 = new List<Users1>(); for (int i = 0; i < dt.Rows.Count; i++) { lus1.Add(new Users1 { Id = Convert.ToInt32(dt.Rows[i][0]), Name = dt.Rows[i][1].ToString(), Company = dt.Rows[i][2].ToString(), IsDelete = Convert.ToBoolean(dt.Rows[i][3]) }); } this.dataGrid1.ItemsSource = lus1; } #endregion #region 刪除 private void DeleteUser(int Id) { try { ConnOpen(); string strSql = string.Format("delete from Users where Id={0}", Id); OleDbCommand cmd = new OleDbCommand(strSql, conn); int a = cmd.ExecuteNonQuery(); ConnClose(); if (a > 0) { conns(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion #region 修改 private void UpdateUser(string Name, string Company, bool IsDelete, int Id) { try { ConnOpen(); string strSql = string.Format("update Users set Name='{0}',Company='{1}',IsDelete={2} where Id={3}", Name, Company, IsDelete, Id); OleDbCommand cmd = new OleDbCommand(strSql, conn); int a = cmd.ExecuteNonQuery(); ConnClose(); if (a > 0) { conns(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } //一個單元格結束編輯后 //private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) //{ // MessageBox.Show("123123"); //} //一行結束編輯后 //private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) //{ // MessageBox.Show("345345"); //} #endregion #region 添加 public void AddUser(string Name, string Company, bool? IsDelete) { try { ConnOpen(); //如果為空,默認設置為有效(未刪除) if (IsDelete == null) IsDelete = false; string strSql = string.Format("insert into Users(Name,Company,IsDelete) values('{0}','{1}',{2})", Name, Company, IsDelete); OleDbCommand cmd = new OleDbCommand(strSql, conn); int a = cmd.ExecuteNonQuery(); ConnClose(); if (a > 0) { conns(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion #region gridcontrol設置 public void set() { //dataGrid1.OptionsView.ShowGroupPanel = false; //dataGrid1.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; //dataGrid1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; } #endregion #endregion } }
Users1類:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExerciseModel { public class Users1 : INotifyPropertyChanged { private int id; private string name; private string company; private bool isDelete; public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public int Id { get { return id; } set { id = value; OnPropertyChanged("Id"); } } public string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } public string Company { get { return company; } set { company = value; OnPropertyChanged("Company"); } } public bool IsDelete { get { return isDelete; } set { isDelete = value; OnPropertyChanged("IsDelete"); } } } }
點擊修改運行的窗體效果圖:
這個窗體的XAML:
<Window x:Class="WpfAppFirst.UpdateUser" 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:local="clr-namespace:WpfAppFirst" mc:Ignorable="d" Title="UpdateUser" Height="327.988" Width="349.854" Loaded="Window_Loaded"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Border Grid.ColumnSpan="2"> <Label Content="修改" Foreground="#000" FontSize="24" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> <Border Grid.Row="1" Grid.ColumnSpan="2"> <Label Content="編號:" FontSize="16" Foreground="#000" VerticalContentAlignment="Center" Padding="50,0,0,0"></Label> </Border> <Border Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2"> <Label x:Name="Ids" FontSize="14" Foreground="#000" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> <Border Grid.Row="2" Grid.ColumnSpan="2"> <Label Content="負責人:" FontSize="16" Foreground="#000" VerticalContentAlignment="Center" Padding="50,0,0,0"></Label> </Border> <Border Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2"> <TextBox x:Name="UName" Background="AliceBlue" Height="30" Width="160"></TextBox> </Border> <Border Grid.Row="3" Grid.ColumnSpan="2"> <Label Content="負責人單位:" FontSize="16" Foreground="#000" VerticalContentAlignment="Center" Padding="50,0,0,0"></Label> </Border> <Border Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2"> <TextBox x:Name="UCompany" Background="AliceBlue" Height="30" Width="160"></TextBox> </Border> <Border Grid.Row="4" Grid.ColumnSpan="2"> <Label Content="狀態:" FontSize="16" Foreground="#000" VerticalContentAlignment="Center" Padding="50,0,0,0"></Label> </Border> <Border Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2"> <ComboBox x:Name="UIsDelete" Background="AliceBlue" Height="30" Width="160"> <ComboBoxItem IsSelected="True">有效</ComboBoxItem> <ComboBoxItem>無效</ComboBoxItem> </ComboBox> </Border> <Border Grid.Row="5" Grid.ColumnSpan="1"> <Border Background="Aquamarine" CornerRadius="2,2,2,2" Width="100" Height="30" Cursor="Hand" MouseLeftButtonDown="Border_MouseLeftButtonDown"> <Label Content="確定" FontSize="16" Foreground="#000" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> </Border> <Border Grid.Row="5" Grid.Column="5" Grid.ColumnSpan="1"> <Border Background="Aquamarine" CornerRadius="2,2,2,2" Width="100" Height="30" Cursor="Hand" MouseLeftButtonDown="Border_MouseLeftButtonDown_1"> <Label Content="取消" FontSize="16" Foreground="#000" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label> </Border> </Border> </Grid> </Window>
然后后台隱藏代碼:
using ExerciseModel; 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.Shapes; namespace WpfAppFirst { /// <summary> /// UpdateUser.xaml 的交互邏輯 /// </summary> public partial class UpdateUser : Window { public UpdateUser() { InitializeComponent(); } #region 連接開關 OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\用戶目錄\\我的文檔\\Access\\Organization.mdb"); //Jet OLEDB:Database Password= public void ConnOpen() { if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } } public void ConnClose() { if (conn.State == System.Data.ConnectionState.Open) { conn.Close(); } } #endregion private void UUser(string Name, string Company, bool IsDelete, int Id) { try { ConnOpen(); string strSql = string.Format("update Users set Name='{0}',Company='{1}',IsDelete={2} where Id={3}", Name, Company, IsDelete, Id); OleDbCommand cmd = new OleDbCommand(strSql, conn); int a = cmd.ExecuteNonQuery(); ConnClose(); if (a > 0) { MessageBox.Show("已修改"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } #region 查詢 public DataTable SelectUser(int id) { OleDbCommand cmd = conn.CreateCommand(); string sql = string.Format("select * from Users where id={0}", id); cmd.CommandText = sql; ConnOpen(); OleDbDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); if (dr.HasRows) { for (int i = 0; i < dr.FieldCount; i++) { dt.Columns.Add(dr.GetName(i)); } dt.Rows.Clear(); } while (dr.Read()) { DataRow row = dt.NewRow(); for (int i = 0; i < dr.FieldCount; i++) { row[i] = dr[i]; } dt.Rows.Add(row); } cmd.Dispose(); ConnClose(); return dt; //List<Users1> lus1 = new List<Users1>(); //for (int i = 0; i < dt.Rows.Count; i++) //{ // lus1.Add(new Users1 { Id = Convert.ToInt32(dt.Rows[i][0]), Name = dt.Rows[i][1].ToString(), Company = dt.Rows[i][2].ToString(), IsDelete = Convert.ToBoolean(dt.Rows[i][3]) }); //} } #endregion /// <summary> /// 修改 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { bool bl = false; if (this.UIsDelete.Text == "有效") bl = true; UUser(this.UName.Text, this.UCompany.Text, bl, Convert.ToInt32(this.Ids.Content)); } /// <summary> /// 取消 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Border_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e) { this.Close(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var sour = SelectUser(Convert.ToInt32(this.Ids.Content)); this.UName.Text = sour.Rows[0]["Name"].ToString(); this.UCompany.Text = sour.Rows[0]["Company"].ToString(); this.UIsDelete.SelectedItem = sour.Rows[0]["IsDelete"].ToString(); } } }