1、基础框架准备工作
1.1 UI层建立wpf应用程序EmployeeListUI.xaml与EmployeeListEdit.xaml;Model层建立Employee类, DAL层建立EmployeeDAL类。
1.2 创建数据库表
USE [HRMSYSDB] GO /****** Object: Table [dbo].[T_Employee] Script Date: 05/15/2013 11:22:50 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[T_Employee]( [Id] [uniqueidentifier] NOT NULL, [Number] [nvarchar](50) NOT NULL, [Name] [nvarchar](50) NOT NULL, [BirthDay] [datetime] NOT NULL, [InDate] [datetime] NOT NULL, [MarriageId] [uniqueidentifier] NOT NULL, [PartyStatusId] [uniqueidentifier] NOT NULL, [Nationality] [nvarchar](50) NOT NULL, [NativeAddr] [nvarchar](250) NOT NULL, [EducationId] [uniqueidentifier] NOT NULL, [Major] [nvarchar](50) NULL, [School] [nvarchar](50) NULL, [Address] [nvarchar](250) NOT NULL, [BaseSalary] [int] NOT NULL, [Email] [nvarchar](50) NULL, [IdNum] [nvarchar](50) NOT NULL, [TelNum] [nvarchar](50) NOT NULL, [EmergencyContact] [nvarchar](max) NULL, [DepartmentId] [uniqueidentifier] NOT NULL, [Position] [nvarchar](50) NOT NULL, [ContractStartDay] [datetime] NOT NULL, [ContractEndDay] [datetime] NOT NULL, [Resume] [nvarchar](max) NULL, [Remarks] [nvarchar](max) NULL, [IsStopped] [bit] NOT NULL, [GenderId] [uniqueidentifier] NOT NULL, [Photo] [image] NULL, CONSTRAINT [PK_T_Employee] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'工号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'Number' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'入职时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'InDate' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'婚姻状况' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'MarriageId' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'政治面貌' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'PartyStatusId' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'民族' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'Nationality' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'籍贯' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'NativeAddr' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'学历' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'EducationId' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'专业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'Major' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'毕业院校' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'School' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'联系地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'Address' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'基本工资' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'BaseSalary' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'身份证号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'IdNum' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'电话号码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'TelNum' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'紧急联系人' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Employee', @level2type=N'COLUMN',@level2name=N'EmergencyContact' GO
2、Model层建立Employee类
与数据库表的字段对应,包括名称、类型,如数据字段为空者需要在类型后加?,因需要跨项目需要加public。
namespace HRMSys.Model { public class T_Employee { public System.Guid Id { get; set; } public System.String Number { get; set; } public System.String Name { get; set; } public System.DateTime BirthDay { get; set; } public System.DateTime InDate { get; set; } public System.Guid MarriageId { get; set; } public System.Guid PartyStatusId { get; set; } public System.String Nationality { get; set; } public System.String NativeAddr { get; set; } public System.Guid EducationId { get; set; } public System.String? Major { get; set; } public System.String? School { get; set; } public System.String Address { get; set; } public System.Int32 BaseSalary { get; set; } public System.String? Email { get; set; } public System.String IdNum { get; set; } public System.String TelNum { get; set; } public System.String? EmergencyContact { get; set; } public System.Guid DepartmentId { get; set; } public System.String Position { get; set; } public System.DateTime ContractStartDay { get; set; } public System.DateTime ContractEndDay { get; set; } public System.String? Resume { get; set; } public System.String? Remarks { get; set; } public System.Boolean IsStopped { get; set; } public System.Guid GenderId { get; set; } public System.Byte[] Photo { get; set; } } }
3、DAL层建立EmployeeDAL类
namespace HRMSys.DAL { public class EmployeeDAL { private Employee ToEmployee(DataRow row) { Employee employee = new Employee(); employee.Address = (string)row["Address"]; employee.BaseSalary = (int)row["BaseSalary"]; employee.BirthDay = (DateTime)row["BirthDay"]; employee.ContractEndDay = (DateTime)row["ContractEndDay"]; employee.ContractStartDay = (DateTime)row["ContractStartDay"]; employee.DepartmentId = (Guid)row["DepartmentId"]; employee.EducationId = (Guid)row["EducationId"]; employee.Email = (string)row["Email"]; employee.EmergencyContact = (string)SqlHelper.FromDbValue(row["EmergencyContact"]); employee.GenderId = (Guid)row["GenderId"]; employee.Id = (Guid)row["Id"]; employee.IdNum = (string)row["IdNum"]; employee.InDate = (DateTime)row["InDate"]; employee.Major = (string)row["Major"]; employee.MarriageId = (Guid)row["MarriageId"]; employee.Name = (string)row["Name"]; employee.Nationality = (string)row["Nationality"]; employee.NativeAddr = (string)row["NativeAddr"]; employee.Number = (string)row["Number"]; employee.PartyStatusId = (Guid)row["PartyStatusId"]; employee.Position = (string)row["Position"]; employee.Remarks = (string)SqlHelper.FromDbValue(row["Remarks"]); employee.Resume = (string)SqlHelper.FromDbValue(row["Resume"]); employee.School = (string)SqlHelper.FromDbValue(row["School"]); employee.TelNum = (string)row["TelNum"]; //todo:如果员工非常多,那么Photo会增加内存占用 employee.Photo = (byte[])SqlHelper.FromDbValue(row["Photo"]); return employee; } public Employee[] ListAll() { DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM T_Employee where IsStopped = 0"); Employee[] empl = new Employee[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { empl[i] = ToEmployee(dt.Rows[i]); //DataRow row = dt.Rows[i]; //Employee emp = new Employee(); //emp.Id =(Guid) row["Id"]; //empl[i] = emp; } return empl; } public void Insert(Employee employee) { SqlHelper.ExecuteNonQuery(@"INSERT INTO [T_Employee] ([Id],[Number],[Name],[BirthDay],[InDate],[MarriageId],[PartyStatusId],[Nationality] ,[NativeAddr],[EducationId],[Major],[School],[Address],[BaseSalary],[Email] ,[IdNum],[TelNum],[EmergencyContact],[DepartmentId],[Position],[ContractStartDay] ,[ContractEndDay],[Resume],[Remarks],[IsStopped],[GenderId],[Photo]) VALUES(newid(),@Number,@Name,@BirthDay,@InDate,@MarriageId,@PartyStatusId,@Nationality ,@NativeAddr,@EducationId,@Major,@School,@Address,@BaseSalary,@Email ,@IdNum,@TelNum,@EmergencyContact,@DepartmentId,@Position,@ContractStartDay ,@ContractEndDay,@Resume,@Remarks,0,@GenderId,@Photo)", new SqlParameter("@Number", employee.Number) , new SqlParameter("@Name", employee.Name) , new SqlParameter("@BirthDay", employee.BirthDay) , new SqlParameter("@InDate", employee.InDate) , new SqlParameter("@MarriageId", employee.MarriageId) , new SqlParameter("@PartyStatusId", employee.PartyStatusId) , new SqlParameter("@Nationality", employee.Nationality) , new SqlParameter("@NativeAddr", employee.NativeAddr) , new SqlParameter("@EducationId", employee.EducationId) , new SqlParameter("@Major", SqlHelper.ToDbValue(employee.Major)) , new SqlParameter("@School", SqlHelper.ToDbValue(employee.School)) , new SqlParameter("@Address", employee.Address) , new SqlParameter("@BaseSalary", employee.BaseSalary) , new SqlParameter("@Email", SqlHelper.ToDbValue(employee.Email)) , new SqlParameter("@IdNum", employee.IdNum) , new SqlParameter("@TelNum", employee.TelNum) , new SqlParameter("@EmergencyContact", SqlHelper.ToDbValue(employee.EmergencyContact)) , new SqlParameter("@DepartmentId", employee.DepartmentId) , new SqlParameter("@Position", employee.Position) , new SqlParameter("@ContractStartDay", employee.ContractStartDay) , new SqlParameter("@ContractEndDay", employee.ContractEndDay) , new SqlParameter("@Resume", SqlHelper.ToDbValue(employee.Resume)) , new SqlParameter("@Remarks", SqlHelper.ToDbValue(employee.Remarks)) , new SqlParameter("@GenderId", employee.GenderId) , new SqlParameter("@Photo",SqlHelper.ToDbValue(employee.Photo))); } ////// 软删除 /// /// public void Deletet(Guid Id) { SqlHelper.ExecuteNonQuery("update T_Employee set IsStopped = 1 where Id = @Id", new SqlParameter("@Id",Id)); } /// /// GetByid,根据ID取得值,如果为空者取null,如果多个ID,者报错 /// /// /// public Employee GetById(Guid id) { DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM T_Employee where IsStopped = 0 and Id=@Id", new SqlParameter("@Id",id)); if (dt.Rows.Count < 0) { return null; } else if (dt.Rows.Count == 1) { return ToEmployee(dt.Rows[0]); } else { throw new Exception(); } } /// ///Update /// /// public void Update(Employee employee) { SqlHelper.ExecuteNonQuery(@"Update T_Employee set [Number]=@Number,[Name]=@Name,[BirthDay]=@BirthDay,[InDate]=@InDate, [MarriageId]=@MarriageId,[PartyStatusId]=@PartyStatusId,[Nationality]=@Nationality, [NativeAddr]=@NativeAddr,[EducationId]=@EducationId,[Major]=@Major,[School]=@School, [Address]=@Address,[BaseSalary]=@BaseSalary,[Email]=@Email, [IdNum]=@IdNum,[TelNum]=@TelNum,[EmergencyContact]=@EmergencyContact, [DepartmentId]=@DepartmentId,[Position]=@Position,[ContractStartDay]=@ContractStartDay, [ContractEndDay]=@ContractEndDay,[Resume]=@Resume,[Remarks]=@Remarks,[GenderId]=@GenderId,[Photo] = @Photo Where Id=@Id", new SqlParameter("@Number", employee.Number) , new SqlParameter("@Name", employee.Name) , new SqlParameter("@BirthDay", employee.BirthDay) , new SqlParameter("@InDate", employee.InDate) , new SqlParameter("@MarriageId", employee.MarriageId) , new SqlParameter("@PartyStatusId", employee.PartyStatusId) , new SqlParameter("@Nationality", employee.Nationality) , new SqlParameter("@NativeAddr", employee.NativeAddr) , new SqlParameter("@EducationId", employee.EducationId) , new SqlParameter("@Major", SqlHelper.ToDbValue(employee.Major)) , new SqlParameter("@School", SqlHelper.ToDbValue(employee.School)) , new SqlParameter("@Address", employee.Address) , new SqlParameter("@BaseSalary", employee.BaseSalary) , new SqlParameter("@Email", SqlHelper.ToDbValue(employee.Email)) , new SqlParameter("@IdNum", employee.IdNum) , new SqlParameter("@TelNum", employee.TelNum) , new SqlParameter("@EmergencyContact", SqlHelper.ToDbValue(employee.EmergencyContact)) , new SqlParameter("@DepartmentId", employee.DepartmentId) , new SqlParameter("@Position", employee.Position) , new SqlParameter("@ContractStartDay", employee.ContractStartDay) , new SqlParameter("@ContractEndDay", employee.ContractEndDay) , new SqlParameter("@Resume", SqlHelper.ToDbValue(employee.Resume)) , new SqlParameter("@Remarks", SqlHelper.ToDbValue(employee.Remarks)) , new SqlParameter("@GenderId", employee.GenderId) , new SqlParameter("@Id", employee.Id) , new SqlParameter("@Photo",employee.Photo)); } public Employee[] Search(string sql,List parameter) { DataTable dt = SqlHelper.ExecuteDataTable(sql,parameter.ToArray()); Employee[] empl = new Employee[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { empl[i] = ToEmployee(dt.Rows[i]); } return empl; } //根据部门查询部门下的所有员工 /// /// 查询部门下的所有员工 /// /// /// public Employee[] ListByDepmentId(Guid deptiId) { DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM T_Employee where DepartmentId=@Id", new SqlParameter("@Id", deptiId)); return ToEmployees(dt); //可以凌下述内容封装一个方法 // Employee[] empl = new Employee[dt.Rows.Count]; //for (int i = 0; i < dt.Rows.Count; i++) //{ // empl[i] = ToEmployee(dt.Rows[i]); //} //return empl } private Employee[] ToEmployees(DataTable table) { Employee[] items = new Employee[table.Rows.Count]; for (int i = 0; i < table.Rows.Count; i++) { items[i] = ToEmployee(table.Rows[i]); } return items; } } }
4、EmployeeListUI界面与交换
4.1 UI
<Window x:Class="HRMSys.UI.SystemMgr.EmployeeListUI" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="员工管理" Height="700" Icon="/images/app.ico" Width="1000" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded_1" > <Grid> <DockPanel> <ToolBar Height="30" DockPanel.Dock="Top"> <Button Name="btnAdd" Click="btnAdd_Click"> <Image Source="/images/add.ico">Image> Button> <Button Name="btnEdit" Click="btnEdit_Click"> <Image Source="/images/edit.ico">Image> Button> <Button Name="bthDelete" Click="bthDelete_Click"> <Image Source="/images/delete.ico">Image> Button> <Button Name="btExport" Click="btExport_Click"> <Image Source="/images/export.ico">Image> Button> ToolBar> <GroupBox Header="搜索" Height="100" DockPanel.Dock="Top"> <Grid> <CheckBox Name="cbSearchByName" Content="姓名" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,0,0,0"/> <TextBox Name="txtName" HorizontalAlignment="Left" Height="24" Margin="57,-4,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/> <CheckBox Name="cbSearchByInDate" Content="入职时间" HorizontalAlignment="Left" Margin="219,0,0,0" VerticalAlignment="Top"/> <DatePicker Name="dpInDateStart" HorizontalAlignment="Left" Margin="302,-4,0,0" VerticalAlignment="Top"/> <TextBlock HorizontalAlignment="Left" Margin="389,0,0,0" TextWrapping="Wrap" Text="至" VerticalAlignment="Top"/> <DatePicker Name="dpInDateEnd" HorizontalAlignment="Left" Margin="415,-4,0,0" VerticalAlignment="Top"/> <CheckBox Name="cbSearchByDept" Content="部门" HorizontalAlignment="Left" Margin="10,37,0,0" VerticalAlignment="Top"/> <ComboBox Name="cmbDept" DisplayMemberPath="Name" SelectedValuePath="Id" HorizontalAlignment="Left" Margin="57,34,0,0" VerticalAlignment="Top" Width="120"/> <Button Content="查询" Name="btnSearch" HorizontalAlignment="Left" Margin="521,34,0,0" VerticalAlignment="Top" Width="75" Click="btnSearch_Click" RenderTransformOrigin="1.187,0.545"/> <CheckBox x:Name="cbSearchByBaseSalary" Content="基本工资" HorizontalAlignment="Left" Margin="219,37,0,0" VerticalAlignment="Top"/> <TextBox x:Name="cbBaseSalarEnd" HorizontalAlignment="Left" Height="23" Margin="415,33,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="82"/> <TextBlock HorizontalAlignment="Left" Margin="389,36,0,0" TextWrapping="Wrap" Text="---" VerticalAlignment="Top"/> <TextBox x:Name="cbBaseSalarStart" HorizontalAlignment="Left" Height="23" Margin="302,33,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="82"/> Grid> GroupBox> <DataGrid Name="gridEmployee" IsReadOnly="True" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Width="100" Binding="{Binding Name}">DataGridTextColumn> <DataGridTextColumn Header="工号" Width="100" Binding="{Binding Number}">DataGridTextColumn> <DataGridTextColumn Header="入职时间" Width="100" Binding="{Binding InDate}">DataGridTextColumn> <DataGridComboBoxColumn Header="学历" Width="80" SelectedValueBinding="{Binding EducationId}" SelectedValuePath="Id" DisplayMemberPath="Name" x:Name="columnEducationId">DataGridComboBoxColumn> <DataGridTextColumn Header="毕业院校" Width="100" Binding="{Binding School}">DataGridTextColumn> <DataGridTextColumn Header="基本工资" Binding="{Binding BaseSalary}">DataGridTextColumn> <DataGridComboBoxColumn Header="部门" Width="100" SelectedValueBinding="{Binding DepartmentId}" SelectedValuePath="Id" DisplayMemberPath="Name" x:Name="columnDepartmentId">DataGridComboBoxColumn> <DataGridTextColumn Header="职位" Width="100" Binding="{Binding Position}">DataGridTextColumn> <DataGridTextColumn Header="合同签订日" Width="100" Binding="{Binding ContractStartDay}">DataGridTextColumn> <DataGridTextColumn Header="合同到期日" Width="100" Binding="{Binding ContractEndDay}">DataGridTextColumn> DataGrid.Columns> DataGrid> DockPanel> Grid> Window>
4.2 交互
UI层第一次需要引用Model与DAL
namespace HRMSys.UI.SystemMgr { ////// EmployeeListUI.xaml 的交互逻辑 /// public partial class EmployeeListUI : Window { public EmployeeListUI() { InitializeComponent(); } private void btnAdd_Click(object sender, RoutedEventArgs e) { //新增按钮 EmployeeEditUI edit = new EmployeeEditUI(); edit.IsAddNew = true; if (edit.ShowDialog() == true) { LoadData(); } } private void Window_Loaded_1(object sender, RoutedEventArgs e) { //column中的部门与学历 columnDepartmentId.ItemsSource = new DepartmentDAL().ListAll(); columnEducationId.ItemsSource = new IdNameDAL().GetByCategory("学历"); LoadData(); cbSearchByName.IsChecked = true; cbSearchByDept.IsChecked = true; cbSearchByBaseSalary.IsChecked = true; dpInDateStart.SelectedDate = DateTime.Today.AddMonths(-1); dpInDateEnd.SelectedDate = DateTime.Today; cmbDept.ItemsSource = new DepartmentDAL().ListAll(); } private void LoadData() { gridEmployee.ItemsSource = new EmployeeDAL().ListAll(); } private void bthDelete_Click(object sender, RoutedEventArgs e) { Employee empl = (Employee)gridEmployee.SelectedItem; if (empl == null) { MessageBox.Show("没有选中任何数据"); return; } else if (MessageBox.Show("你真的要删除吗", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { new EmployeeDAL().Deletet(empl.Id); LoadData(); } } private void btnEdit_Click(object sender, RoutedEventArgs e) { Employee empl = (Employee)gridEmployee.SelectedItem; if (empl == null) { MessageBox.Show("你没有选择任何行!"); return; } EmployeeEditUI edit = new EmployeeEditUI(); edit.EditingId = empl.Id; edit.IsAddNew = false; if (edit.ShowDialog() == true) { LoadData(); } } private void btnSearch_Click(object sender, RoutedEventArgs e) { //搜索 List<string> whereList = new List<string>(); List parameter = new List (); if (cbSearchByName.IsChecked == true) { whereList.Add("Name=@Name"); parameter.Add(new SqlParameter("@Name",txtName.Text)); } if (cbSearchByInDate.IsChecked == true) { whereList.Add("InDate>=@InDateStart and InDate<=@InDateEnd"); parameter.Add(new SqlParameter("@InDateStart", dpInDateStart.SelectedDate)); parameter.Add(new SqlParameter("@InDateEnd", dpInDateEnd.SelectedDate)); } if (cbSearchByDept.IsChecked == true) { whereList.Add("DepartmentId=@DepartmentId"); parameter.Add(new SqlParameter("@DepartmentId", cmbDept.SelectedValue)); } if (cbSearchByBaseSalary.IsChecked == true) { whereList.Add("BaseSalary>=@BaseSalaryStart and BaseSalary<@BaseSalaryEnd"); parameter.Add(new SqlParameter("@BaseSalaryStart", cbBaseSalarStart.Text)); parameter.Add(new SqlParameter("@BaseSalaryEnd", cbBaseSalarEnd.Text)); } string whereSql = string.Join(" and ",whereList); string sql = "select * from T_Employee"; if (whereSql.Length > 0) { sql = sql + " where " + whereSql; } Employee[] result = new EmployeeDAL().Search(sql, parameter); gridEmployee.ItemsSource = result; } private void btExport_Click(object sender, RoutedEventArgs e) { SaveFileDialog sdfExport = new SaveFileDialog(); sdfExport.Filter = "Excel文件|*.xls"; if (sdfExport.ShowDialog() != true) { return; } string filename = sdfExport.FileName; HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("员工数据"); IRow rowHeader = sheet.CreateRow(0);//表头行 rowHeader.CreateCell(0, CellType.STRING).SetCellValue("姓名"); rowHeader.CreateCell(1, CellType.STRING).SetCellValue("工号"); rowHeader.CreateCell(2, CellType.STRING).SetCellValue("入职日期"); //把查询结果导出到Excel Employee[] employees = (Employee[])gridEmployee.ItemsSource; for (int i = 0; i < employees.Length; i++) { Employee employee = employees[i]; IRow row = sheet.CreateRow(i + 1); row.CreateCell(0, CellType.STRING).SetCellValue(employee.Name); row.CreateCell(1, CellType.STRING).SetCellValue(employee.Number); ICellStyle styledate = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); //格式具体有哪些请看单元格右键中的格式,有说明 styledate.DataFormat = format.GetFormat("yyyy\"年\"m\"月\"d\"日\""); ICell cellInDate = row.CreateCell(2, CellType.NUMERIC); cellInDate.CellStyle = styledate; cellInDate.SetCellValue(employee.InDate); } using (Stream stream = File.OpenWrite(filename)) { workbook.Write(stream); } } } }
5、EmployeeEditiUI UI界面与交互
5.1 UI
<Window x:Class="HRMSys.UI.SystemMgr.EmployeeEditUI" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfmedia="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit" Title="员工添加编辑" Height="650" Width="800" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" Loaded="Window_Loaded_2"> <Grid Name="gridEmployee"> <TabControl> <TabItem Header="基本信息"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="18*"/> <ColumnDefinition Width="179*"/> Grid.ColumnDefinitions> <TextBlock HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="姓名" VerticalAlignment="Top"/> <TextBox Text="{Binding Name}" HorizontalAlignment="Left" Height="23" Margin="39,9,0,0" TextWrapping="Wrap" Name="txtName" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="108,14,0,0" TextWrapping="Wrap" Text="性别" VerticalAlignment="Top" Grid.Column="1"/> <ComboBox Text="必填" x:Name="cbGender" SelectedValue="{Binding GenderId}" DisplayMemberPath="Name" SelectedValuePath="Id" HorizontalAlignment="Left" Margin="151,9,0,0" VerticalAlignment="Top" Width="120" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="290,11,0,0" TextWrapping="Wrap" Text="出生日期" VerticalAlignment="Top" Grid.Column="1"/> <DatePicker x:Name="dpBirthDay" SelectedDate="{Binding BirthDay}" HorizontalAlignment="Left" Margin="355,5,0,0" VerticalAlignment="Top" Width="140" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,46,0,0" TextWrapping="Wrap" Text="入职日期" VerticalAlignment="Top"/> <DatePicker SelectedDate="{Binding InDate}" x:Name="dpInDate" HorizontalAlignment="Left" Margin="5,42,0,0" VerticalAlignment="Top" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="108,46,0,0" TextWrapping="Wrap" Text="合同签订日" VerticalAlignment="Top" Grid.Column="1"/> <DatePicker x:Name="dpContractBeginDate" SelectedDate="{Binding ContractStartDay}" HorizontalAlignment="Left" Margin="189,42,0,0" VerticalAlignment="Top" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="290,46,0,0" TextWrapping="Wrap" Text="合同到期日" VerticalAlignment="Top" Grid.Column="1"/> <DatePicker x:Name="dpContractEndDate" SelectedDate="{Binding ContractEndDay}" HorizontalAlignment="Left" Margin="355,42,0,0" VerticalAlignment="Top" Width="140" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,79,0,0" TextWrapping="Wrap" Text="婚姻状况" VerticalAlignment="Top"/> <ComboBox x:Name="cbMarriage" SelectedValue="{Binding MarriageId}" DisplayMemberPath="Name" SelectedValuePath="Id" HorizontalAlignment="Left" Margin="63,73,0,0" VerticalAlignment="Top" Width="96" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="108,79,0,0" TextWrapping="Wrap" Text="政治面貌" VerticalAlignment="Top" Grid.Column="1"/> <ComboBox x:Name="cbPartyStatus" SelectedValue="{Binding PartyStatusId}" DisplayMemberPath="Name" SelectedValuePath="Id" HorizontalAlignment="Left" Margin="178,73,0,0" VerticalAlignment="Top" Width="93" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="289,78,0,0" TextWrapping="Wrap" Text="民族" VerticalAlignment="Top" Grid.Column="1"/> <TextBox x:Name="txtNational" HorizontalAlignment="Left" Height="23" Margin="355,79,0,0" TextWrapping="Wrap" Text="{Binding Nationality}" VerticalAlignment="Top" Width="140" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,111,0,0" TextWrapping="Wrap" Text="籍贯" VerticalAlignment="Top"/> <TextBox x:Name="txtNativeAddr" HorizontalAlignment="Left" Height="23" Margin="39,110,0,0" TextWrapping="Wrap" Text="{Binding NativeAddr}" VerticalAlignment="Top" Width="528" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="10,146,0,0" TextWrapping="Wrap" Text="学历" VerticalAlignment="Top"/> <ComboBox x:Name="cbEducation" SelectedValuePath="Id" DisplayMemberPath="Name" SelectedValue="{Binding EducationId}" HorizontalAlignment="Left" Margin="39,146,0,0" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="113,146,0,0" TextWrapping="Wrap" Text="专业" VerticalAlignment="Top" Grid.Column="1"/> <TextBox x:Name="txtMajor" HorizontalAlignment="Left" Height="23" Margin="151,145,0,0" TextWrapping="Wrap" Text="{Binding Major}" VerticalAlignment="Top" Width="120" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="289,146,0,0" TextWrapping="Wrap" Text="毕业院校" VerticalAlignment="Top" Grid.Column="1"/> <TextBox x:Name="txtSchool" HorizontalAlignment="Left" Height="23" Margin="355,145,0,0" TextWrapping="Wrap" Text="{Binding School}" VerticalAlignment="Top" Width="140" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,180,0,0" TextWrapping="Wrap" Text="联系地址" VerticalAlignment="Top"/> <TextBox x:Name="txtAddr" HorizontalAlignment="Left" Height="23" Margin="63,179,0,0" TextWrapping="Wrap" Text="{Binding Address}" VerticalAlignment="Top" Width="504" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="10,215,0,0" TextWrapping="Wrap" Text="基本工资" VerticalAlignment="Top"/> <TextBox x:Name="txtBaseSalary" HorizontalAlignment="Left" Height="23" Margin="63,214,0,0" TextWrapping="Wrap" Text="{Binding BaseSalary}" VerticalAlignment="Top" Width="96" Grid.ColumnSpan="2"/> <TextBox x:Name="txtEmail" HorizontalAlignment="Left" Height="23" Margin="161,214,0,0" TextWrapping="Wrap" Text="{Binding Email}" VerticalAlignment="Top" Width="120" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="108,215,0,0" TextWrapping="Wrap" Text="电子邮件" VerticalAlignment="Top" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="290,214,0,0" TextWrapping="Wrap" Text="联系电话" VerticalAlignment="Top" Grid.Column="1"/> <TextBox x:Name="txtTelNum" HorizontalAlignment="Left" Height="23" Margin="355,213,0,0" TextWrapping="Wrap" Text="{Binding TelNum}" VerticalAlignment="Top" Width="140" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,251,0,0" TextWrapping="Wrap" Text="身份证" VerticalAlignment="Top"/> <TextBox x:Name="txtIdNum" HorizontalAlignment="Left" Height="23" Margin="63,251,0,0" TextWrapping="Wrap" Text="{Binding IdNum}" VerticalAlignment="Top" Width="290" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="295,251,0,0" TextWrapping="Wrap" Text="部门" VerticalAlignment="Top" Grid.Column="1"/> <ComboBox x:Name="cbDepatment" SelectedValue="{Binding DepartmentId}" SelectedValuePath="Id" DisplayMemberPath="Name" HorizontalAlignment="Left" Margin="355,251,0,0" VerticalAlignment="Top" Width="140" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,289,0,0" TextWrapping="Wrap" Text="职位" VerticalAlignment="Top"/> <TextBox x:Name="txtPosition" HorizontalAlignment="Left" Height="23" Margin="63,288,0,0" TextWrapping="Wrap" Text="{Binding Position}" VerticalAlignment="Top" Width="165" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="178,289,0,0" TextWrapping="Wrap" Text="工号" VerticalAlignment="Top" Grid.Column="1"/> <TextBox x:Name="txtNumber" HorizontalAlignment="Left" Height="23" Margin="217,288,0,0" TextWrapping="Wrap" Text="{Binding Number}" VerticalAlignment="Top" Width="278" Grid.Column="1"/> <TextBlock HorizontalAlignment="Left" Margin="10,328,0,0" TextWrapping="Wrap" Text="紧急联系人信息" VerticalAlignment="Top" Grid.ColumnSpan="2"/> <TextBox x:Name="txtEmergencyContact" HorizontalAlignment="Left" TextWrapping="Wrap" Height="131" Margin="10,348,0,0" Text="{Binding EmergencyContact}" VerticalAlignment="Top" Width="343" Grid.ColumnSpan="2"/> <TextBlock HorizontalAlignment="Left" Margin="290,328,0,0" TextWrapping="Wrap" Text="备注" VerticalAlignment="Top" Grid.Column="1"/> <TextBox x:Name="txtRemarks" HorizontalAlignment="Left" Height="131" Margin="295,348,0,0" TextWrapping="Wrap" Text="{Binding Remarks}" VerticalAlignment="Top" Width="411" Grid.Column="1"/> <Image x:Name="imgPhoto" HorizontalAlignment="Left" Height="215" Margin="511,14,0,0" VerticalAlignment="Top" Width="195" Grid.Column="1" Stretch="Fill" /> <Button x:Name="btnChoosePhoto" Content="选择照片" HorizontalAlignment="Left" Margin="511,251,0,0" VerticalAlignment="Top" Width="75" Grid.Column="1" Click="btnChoosePhoto_Click" /> <Button x:Name="btnCapture" Content="拍照" HorizontalAlignment="Left" Margin="610,249,0,0" VerticalAlignment="Top" Width="75" Grid.Column="1" Click="btnCapture_Click" /> Grid> TabItem> <TabItem Header="简历"> <TextBox TextWrapping="Wrap" Name="txtResume" Text="{Binding Resume}">TextBox> TabItem> TabControl> <Button x:Name="txtSave" Content="保存" HorizontalAlignment="Left" Margin="658,521,0,-44" VerticalAlignment="Top" Width="120" Click="txtSave_Click" Height="39"/> Grid> Window>
5.2 Edit交互
namespace HRMSys.UI.SystemMgr { ////// EmployeeEditUI.xaml 的交互逻辑 /// public partial class EmployeeEditUI : Window { public EmployeeEditUI() { InitializeComponent(); } public Guid EditingId { get; set; } public bool IsAddNew {get;set; } private void Window_Loaded_2(object sender, RoutedEventArgs e) { IdNameDAL idNameDAL = new IdNameDAL(); cbGender.ItemsSource = idNameDAL.GetByCategory("性别"); cbGender.ItemsSource = idNameDAL.GetByCategory("性别"); cbMarriage.ItemsSource = idNameDAL.GetByCategory("婚姻状况"); cbPartyStatus.ItemsSource = idNameDAL.GetByCategory("政治面貌"); cbEducation.ItemsSource = idNameDAL.GetByCategory("学历"); cbDepatment.ItemsSource = new DepartmentDAL().ListAll(); if (IsAddNew) { //插入数据带入初始值 Employee employee = new Employee(); employee.InDate = DateTime.Today;//给默认值 employee.ContractStartDay = DateTime.Today; employee.ContractEndDay = DateTime.Today.AddYears(1); employee.BirthDay = DateTime.Today.AddYears(-30); employee.Nationality = "汉族"; employee.Email = "@szhnd.com.cn"; //手动指定 //employee.Number = "HND"; //系统设定 employee.Number = new T_SettingDAL().GetValue("员工工号前缀"); gridEmployee.DataContext = employee; } else { //这里是更新的初始值 Employee empl = new EmployeeDAL().GetById(EditingId); gridEmployee.DataContext = empl; if (empl.Photo != null) { ShowImg(empl.Photo); } //流操作,将图片显示出来 //建立一个empl.photo所指向的内存流。 //if (empl.Photo != null) //{ // //传入一个Photo数值,取得一个实例 // MemoryStream stream = new MemoryStream(empl.Photo); // BitmapImage image = new BitmapImage(); // image.StreamSource = stream; // imgPhoto.Source = image; //} } } private void txtSave_Click(object sender, RoutedEventArgs e) { bool isOK = true; CheckTextboxNotEmpty(ref isOK, txtName, txtNational, txtNativeAddr, txtAddr, txtBaseSalary, txtTelNum, txtIdNum, txtPosition, txtNumber); CheckComboBoxNotEmpty(ref isOK, cbGender, cbMarriage, cbPartyStatus, cbEducation, cbDepatment); //保存按钮 if (!isOK) { return; } if (IsAddNew) { //这里是新增 Employee employee = (Employee)gridEmployee.DataContext; new EmployeeDAL().Insert(employee); } else { //这里是编辑 Employee empl =(Employee) gridEmployee.DataContext; new EmployeeDAL().Update(empl); } DialogResult = true; } private void CheckTextboxNotEmpty(ref bool isOK, params TextBox[] textboxes) { foreach (TextBox txtBox in textboxes) { if (txtBox.Text.Length <= 0) { isOK = false; txtBox.Background = Brushes.Red; } else { txtBox.Background = null; } } } private void CheckComboBoxNotEmpty(ref bool isOK, params ComboBox[] cmbs) { foreach (ComboBox cmb in cmbs) { if (cmb.SelectedIndex < 0) { isOK = false; cmb.Effect = new DropShadowEffect { Color = Colors.Red }; } else { cmb.Effect = null; } } } private void btnChoosePhoto_Click(object sender, RoutedEventArgs e) { //选择照片 OpenFileDialog ofdPhoto = new OpenFileDialog(); ofdPhoto.Filter = "jpg图片|*.jpg|png图片|*.png"; if (ofdPhoto.ShowDialog() == true) { string filename = ofdPhoto.FileName; Employee employee = (Employee)gridEmployee.DataContext; employee.Photo = File.ReadAllBytes(filename);//读取文件的二进制数据 imgPhoto.Source = new BitmapImage(new Uri(filename)); } } private void ShowImg(byte[] imgBytes) { MemoryStream stream = new MemoryStream(imgBytes); BitmapImage bmpImg = new BitmapImage(); bmpImg.BeginInit(); bmpImg.StreamSource = stream; bmpImg.EndInit(); imgPhoto.Source = bmpImg; } private void btnCapture_Click(object sender, RoutedEventArgs e) { CaptureWindow win = new CaptureWindow(); if (win.ShowDialog() == true) { byte[] data = win.CaptureData; ShowImg(data); Employee employee = (Employee)gridEmployee.DataContext; employee.Photo = data; } } } }