0
点赞
收藏
分享

微信扫一扫

【Tools】微软 Edge 浏览器全解析

小禹说财 2024-07-24 阅读 41
数据库c#

在Windows Forms(WinForms)应用程序中,创建一个通用的管理页面通常涉及对数据的增删改查(CRUD)操作,以及一些额外的功能,如数据过滤、排序、导出和导入等。

先看一个仓库管理页面要素。

仓库管理页面的重点在LoadStore和修改, 代码如下:

using STMS.BLL;
using STMS.Models.DModels;
using STMS.STMSApp.FModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace STMS.STMSApp.store
{
    public partial class FrmStoreList : Form
    {
        public FrmStoreList()
        {
            InitializeComponent();
        }
        StoreBLL storeBLL = new StoreBLL();
        /// <summary>
        /// 页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmStoreList_Load(object sender, EventArgs e)
        {
            chkShowDel.Checked = false;
            txtKeyWords.Clear();
            LoadStoreList();
        }

        /// <summary>
        /// 查询仓库信息列表 
        /// </summary>
        private void LoadStoreList()
        {
            bool isDel = chkShowDel.Checked;
            string keywords = txtKeyWords.Text.Trim();
            dgvStoreList.ShowDgvCols(isDel);//显示操作列
            dgvStoreList.Columns["colAddRegion"].Visible = !isDel;

            //加载仓库数据  到数据库读取数据
            List<StoreInfo> storeList = storeBLL.GetStoreInfos(keywords, isDel);
            if(storeList.Count>0)
            {
                dgvStoreList.AutoGenerateColumns = false;
                dgvStoreList.DataSource = storeList;
                SetEnableBtns(true);
            }
            else
            {
                dgvStoreList.DataSource = null;
                SetEnableBtns(false);
            }

        }

        private void SetEnableBtns(bool blShow)
        {
            btnFind.Enabled = blShow;
            btnDelete.Enabled = blShow;
        }

        private void chkShowDel_CheckedChanged(object sender, EventArgs e)
        {
            LoadStoreList();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFind_Click(object sender, EventArgs e)
        {
            LoadStoreList();
        }

        /// <summary>
        /// 新增仓库信息--打开信息页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            ShowStoreInfoPage(1, 0);
        }

        /// <summary>
        /// 打开仓库信息页   新增、修改页面
        /// </summary>
        /// <param name="actTpye"></param>
        /// <param name="storeId"></param>
        private void ShowStoreInfoPage(int actTpye,int storeId)
        {
            FrmStoreInfo fStore = new FrmStoreInfo();
            fStore.Tag = new FInfoData()
            {
                ActType = actTpye,
                FId = storeId
            };
            //刷新列表页数据效果  委托,采用事件
            fStore.ReLoadList +=()=> LoadStoreList();
            fStore.StartPosition = FormStartPosition.CenterScreen;
            fStore.ShowDialog();
        }

        /// <summary>
        /// 打开仓库分区信息页   添加分区
        /// </summary>
        /// <param name="storeId"></param>
        private void ShowStoreRegionInfoPage(int storeId)
        {
            FrmStoreRegionInfo fRegion= new FrmStoreRegionInfo();
            fRegion.Tag = new FInfoData()
            {
                ActType = 3,
                FId = storeId
            };
            //刷新列表页数据效果  委托,采用事件
            fRegion.ReLoadStoreList += () => LoadStoreList();
            fRegion.StartPosition = FormStartPosition.CenterScreen;
            fRegion.ShowDialog();
        }

        private void dgvStoreList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var cell = dgvStoreList.Rows[e.RowIndex].Cells[e.ColumnIndex];//当前点击的单元格
            string headText = cell.FormattedValue.ToString();
            StoreInfo store = dgvStoreList.Rows[e.RowIndex].DataBoundItem as StoreInfo;
            switch(headText)
            {
                case "添加分区":
                    //打开添加仓库分区信息页
                    ShowStoreRegionInfoPage(store.StoreId);
                    break;
                case "修改":
                    //打开仓库信息页
                    ShowStoreInfoPage(2, store.StoreId);
                    break;
                case "删除":
                    //执行逻辑删除(假删除)
                    DeleteStore(store,1);
                    break;
                case "恢复":
                    //恢复(逻辑删除的恢复)
                    DeleteStore(store, 0);
                    break;
                case "移除":
                    //真删除 delete
                    DeleteStore(store,2);
                    break;
            }
        }

        /// <summary>
        /// 删除/恢复/移除仓库信息
        /// </summary>
        /// <param name="storeInfo"></param>
        /// <param name="delCode"></param>
        private void DeleteStore(StoreInfo storeInfo,int delCode)
        {
            string InfoName = "仓库信息";
            string delName = FormUtility.GetDelName(delCode);
            string msgTitle = $"{InfoName}{delName}";
            DialogResult dr= MsgBoxHelper.MsgBoxConfirm(msgTitle, $"你确定要{delName}该{InfoName}吗?");
            if(dr==DialogResult.Yes)
            {
                bool bl = false;
                switch(delCode)
                {
                    case 1://逻辑删除
                        int reDel= storeBLL.LogicDeleteStore(storeInfo.StoreId);
                        if(reDel==1)
                        {
                            bl = true;
                        }
                        else if(reDel==2)
                        {
                            MsgBoxHelper.MsgErrorShow(msgTitle, $"该仓库已添加了分区,不能删除!");
                            return;
                        }
                        else
                        {
                            bl = false;
                        }
                        break;
                    case 0:
                        bl = storeBLL.RecoverStore(storeInfo.StoreId);
                        break;
                    case 2:
                        bl = storeBLL.DeleteStore(storeInfo.StoreId);
                        break;
                }
                if(bl)
                {
                    MsgBoxHelper.MsgBoxShow(msgTitle, $"{InfoName} {delName} 成功!");
                    LoadStoreList();
                }
                else
                {
                    MsgBoxHelper.MsgErrorShow(msgTitle, $"{InfoName} {delName} 失败!");
                    return;
                }
            }
        }

        /// <summary>
        /// 刷新   恢复最初状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            chkShowDel.Checked = false;
            txtKeyWords.Clear();
            LoadStoreList();
        }

        /// <summary>
        /// 批量删除仓库信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            string msgTitle = "仓库信息删除";
            List<int> delIds = new List<int>();
            foreach(DataGridViewRow dr in dgvStoreList.Rows)
            {
                StoreInfo store = dr.DataBoundItem as StoreInfo;
                DataGridViewCheckBoxCell chkCell = dr.Cells["colChk"] as DataGridViewCheckBoxCell;
                if(chkCell.FormattedValue.ToString()=="True")
                {
                    delIds.Add(store.StoreId);
                }
            }
            if(delIds.Count >0)
            {
                DialogResult dr = MsgBoxHelper.MsgBoxConfirm(msgTitle, $"你确定要删除选择的仓库信息吗?");
                if(dr==DialogResult.Yes)
                {
                    string reStr= storeBLL.LogicDeleteStore(delIds);
                    if(reStr=="Y")//成功
                    {
                        MsgBoxHelper.MsgBoxShow(msgTitle, "选择的仓库信息删除 成功!");
                        LoadStoreList();
                    }
                    else if(reStr.Length>=1&&(reStr!="Y"||reStr!="0"))//存在分区的仓库
                    {
                        MsgBoxHelper.MsgErrorShow(msgTitle, "选择的仓库信息中存在有已添加分区的仓库,它们的编号是:" + reStr);
                        return;
                    }
                    else//删除失败
                    {
                        MsgBoxHelper.MsgErrorShow(msgTitle, "选择的仓库信息删除失败!");
                        return;
                    }
                }
            }
            else
            {
                MsgBoxHelper.MsgErrorShow(msgTitle, "请选择要删除的仓库信息!");
                return;
            }
        }
    }
}

下面是一个概述,说明如何实现一个通用的管理页面,以员工信息管理为例。

1. 设计用户界面

  • DataGridView控件:用于展示数据表格,支持数据绑定和事件处理。
  • TextBoxes和ComboBoxes:用于输入或选择数据,如员工姓名、职位等。
  • Buttons:用于执行CRUD操作,如添加、编辑、删除和保存。
  • Labels和Messages:用于显示提示信息或操作结果。

2. 实现数据绑定

  • 使用ADO.NET(如SqlDataAdapter和DataSet)或Entity Framework来连接数据库。
  • 将DataGridView与数据源绑定,确保数据能够实时更新。

3. CRUD操作

  • 添加(Create):当用户点击“添加”按钮时,显示一个表单或对话框让用户输入数据,然后将数据插入数据库。
  • 读取(Read):数据加载时,从数据库中读取数据并填充到DataGridView中。
  • 更新(Update):允许用户直接在DataGridView中编辑数据,或通过弹出的编辑对话框进行修改,然后更新数据库。
  • 删除(Delete):当用户选择一行并点击“删除”按钮时,从数据库中删除对应的数据行。

4. 高级功能

  • 数据过滤和排序:允许用户通过ComboBox或TextBox过滤数据,以及通过列标题排序数据。
  • 数据导出和导入:提供导出数据到Excel或CSV文件的功能,以及导入数据从这些文件。
  • 权限控制:根据用户的权限显示或禁用某些功能,如只读访问或编辑权限。

5. 事件处理

  • RowValidating:在用户试图保存更改之前,验证数据的完整性。
  • RowUpdating:在数据更新到数据库之前,捕获更改并执行必要的逻辑。
  • CellClick:当用户点击单元格时,显示详细信息或启用编辑模式。

6. 异常处理

  • 在执行数据库操作时,应捕获并妥善处理异常,向用户提供友好的错误信息。

7. 界面美化

  • 使用样式和主题来美化界面,如背景色、字体、图标等,以提高用户体验。

8. 性能优化

  • 对于大数据集,考虑使用虚拟化和分页技术,避免一次性加载所有数据,提高应用程序的响应速度。

示例代码片段:添加员工信息

 

Csharp

1private void btnSave_Click(object sender, EventArgs e)
2{
3    using (SqlConnection connection = new SqlConnection(connectionString))
4    {
5        string query = "INSERT INTO Employees (Name, Position, Department) VALUES (@Name, @Position, @Department)";
6        using (SqlCommand command = new SqlCommand(query, connection))
7        {
8            command.Parameters.AddWithValue("@Name", txtName.Text);
9            command.Parameters.AddWithValue("@Position", cmbPosition.SelectedItem);
10            command.Parameters.AddWithValue("@Department", cmbDepartment.SelectedItem);
11            
12            connection.Open();
13            int rowsAffected = command.ExecuteNonQuery();
14            if (rowsAffected > 0)
15            {
16                MessageBox.Show("员工信息已成功添加!");
17                // 刷新DataGridView
18                RefreshDataGridView();
19            }
20            else
21            {
22                MessageBox.Show("添加员工信息时发生错误。");
23            }
24        }
25    }
26}

通过上述步骤,你可以构建一个功能齐全、易于维护的WinForms管理页面,用于处理各种类型的数据管理任务。

举报

相关推荐

0 条评论