DataGridView CellValueChanged CurrentCellDirtyStateChanged

1、CellValueChanged 失去焦点触发

2、CurrentCellDirtyStateChanged

private void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    if (dgv.IsCurrentCellDirty)
    {
        dgv.CommitEdit(
            DataGridViewDataErrorContexts.Commit);
    }
}

 3、DataGridView

using Library.BLL;
using Library.Models;
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 Library.UI
{
    public partial class BookListFrm : Form
    {
        // 图书信息
        private readonly BookInfoBLL _bookInofBLL = new BookInfoBLL();
        // 类型
        private readonly BookTypeBLL _bookTypeBLL = new BookTypeBLL();
        private readonly List<BookTypeInfo> _bookTypeInfos = new List<BookTypeInfo>();
        // 图书ids
        private readonly List<int> _bookIdLst = new List<int>();

        public BookListFrm()
        {
            InitializeComponent();
            _bookTypeInfos = _bookTypeBLL.GetBookTypeInfos();
        }

        private void BookListFrm_Load(object sender, EventArgs e)
        {
            //_bookinfoList = _bookInofBLL.GetAllBookInfo();
            // 加载 TreeView
            LoadTrvType();
            // 加载 combox
            LoadTypeCombox();
            // 获取数据
            FindBookInfos();
        }


        #region 加载 信息
        /// <summary>
        /// 加载 TreeView
        /// </summary>
        private void LoadTrvType() 
        {
            // 根节点
            TreeNode rootNode = new TreeNode
            { 
                Name = "0",
                Text = "所有类别"
            };
            trvType.Nodes.Add(rootNode);
            
            foreach (BookTypeInfo bookType in _bookTypeInfos)
            {
                TreeNode typeNode = new TreeNode 
                {
                    Name = bookType.BookTypeId.ToString(),
                    Text = bookType.BookTypeName
                };
                rootNode.Nodes.Add(typeNode);
            }

        }

        /// <summary>
        /// 加载 类型 下拉框
        /// </summary>
        public void LoadTypeCombox() 
        {
            DataGridViewComboBoxColumn dgvCbo = dgvBook.Columns["colBookTypeId"] as DataGridViewComboBoxColumn;
            dgvCbo.DataSource = _bookTypeInfos;
            dgvCbo.ValueMember = nameof(BookTypeInfo.BookTypeId);
            dgvCbo.DisplayMember = nameof(BookTypeInfo.BookTypeName);
        }

        public void FindBookInfos() 
        {
            // 类型
            string typeId = trvType.SelectedNode?.Name;
            // 名称
            string bookName = txtBookName.Text.Trim();
            // 删除
            int isDeleted = chkDeleted.Checked ? 1 : 0;

            // 获取参数
            List<BookInfo> bookInfos = _bookInofBLL.GetAllBookInfo(typeId, bookName, isDeleted);
            dgvBook.AutoGenerateColumns = false;
            dgvBook.DataSource = bookInfos;

            // 按钮
            bool isShow = chkDeleted.Checked; 
            BtnAdd.Enabled = !isShow;
            BtnDelete.Enabled = !isShow;
            BtnRecover.Enabled = isShow;
            BtnRemove.Enabled = isShow;
            // 列
            dgvBook.Columns["colEdit"].Visible = !isShow;
            dgvBook.Columns["colDelete"].Visible = !isShow;
            dgvBook.Columns["colRecover"].Visible = isShow;
            dgvBook.Columns["colRemove"].Visible = isShow;
        }
        #endregion


        #region 查询
        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSearch_Click(object sender, EventArgs e)
        {
            FindBookInfos();
        }

        /// <summary>
        /// 查询树形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvType_AfterSelect(object sender, TreeViewEventArgs e)
        {
            FindBookInfos();
        }

        /// <summary>
        /// 查询 checkbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkDeleted_CheckedChanged(object sender, EventArgs e)
        {
            FindBookInfos();
        }
        #endregion

        #region 单选框
        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in dgvBook.Rows)
            {
                DataGridViewCheckBoxCell cell = dr.Cells["colChk"] as DataGridViewCheckBoxCell;
                cell.Value = chkAll.Checked;
            }
        }

        /// <summary>
        /// 单元格值 改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvBook_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            // 图书信息
            BookInfo bookInfo = dgvBook.Rows[e.RowIndex].DataBoundItem as BookInfo;
            // 选中/取消
            if (dgvBook.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell cell)
            {
                if (cell.FormattedValue.ToString() == "True")
                {
                    _bookIdLst.Add(bookInfo.BookId);
                }
                else
                {
                    _bookIdLst.Remove(bookInfo.BookId);
                }
            }
        }

        private void dgvBook_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;

            if (dgv.IsCurrentCellDirty)
            {
                dgv.CommitEdit(
                    DataGridViewDataErrorContexts.Commit);
            }
        }


        #endregion

        #region 数据操作
        /// <summary>
        ///  新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            BookInfoFrm bookInfoFrm = new BookInfoFrm(0);
            bookInfoFrm.ReloadBookInfoList += FindBookInfos;
            bookInfoFrm.Show();
        }

        /// <summary>
        /// dgv 操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvBook_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            BookInfo bookInfo = dgvBook.Rows[e.RowIndex].DataBoundItem as BookInfo;
            int bookId = bookInfo.BookId;
            // button
            if (dgvBook.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewButtonCell btnCell)
            {
                if (btnCell.FormattedValue.ToString() == "修改")
                {
                    BookInfoFrm bookInfoFrm = new BookInfoFrm(bookId);
                    bookInfoFrm.ReloadBookInfoList += FindBookInfos;
                    bookInfoFrm.Show();
                }

                if (btnCell.FormattedValue.ToString() == "删除")
                {
                    if (MessageBox.Show("确认是否删除?", "删除提示:", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        bool success = _bookInofBLL.DeleteBookInfoById(bookId);
                        if (success) 
                        {
                            MessageBox.Show("删除成功");
                            FindBookInfos();
                        }
                        else
                        {
                            MessageBox.Show("删除失败");
                        }
                    }
                }

            }

            // link
            if (dgvBook.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell linkCell)
            {
                // 恢复
                if (linkCell.FormattedValue.ToString() == "恢复")
                {
                    bool success = _bookInofBLL.RecoverBookInfoById(bookId);
                    if (success)
                    {
                        MessageBox.Show("恢复成功");
                        FindBookInfos();
                    }
                    else
                    {
                        MessageBox.Show("恢复失败");
                    }
                }

                // 移除
                if (linkCell.FormattedValue.ToString() == "移除")
                {
                    bool success = _bookInofBLL.RemoveBookInfoById(bookId);
                    if (success)
                    {
                        MessageBox.Show("移除成功");
                        FindBookInfos();
                    }
                    else
                    {
                        MessageBox.Show("移除失败");
                    }
                }
            }

        }
        #endregion

        #region 批量数据操作
        
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要批量删除?", "删除提示:", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                bool success = _bookInofBLL.DeleteBookInfoByIds(_bookIdLst);
                if (success)
                {
                    MessageBox.Show("删除成功");
                    FindBookInfos();
                    _bookIdLst.Clear();
                    chkAll.Checked = false;
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
        }

        /// <summary>
        /// 批量恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRecover_Click(object sender, EventArgs e)
        {
            bool success = _bookInofBLL.RecoverBookInfoByIds(_bookIdLst);
            if (success)
            {
                MessageBox.Show("恢复成功");
                FindBookInfos();
                _bookIdLst.Clear();
                chkAll.Checked = false;
            }
            else
            {
                MessageBox.Show("恢复失败");
            }
        }

        private void BtnRemove_Click(object sender, EventArgs e)
        {
            bool success = _bookInofBLL.RemoveBookInfoByIds(_bookIdLst);
            if (success)
            {
                MessageBox.Show("移除成功");
                FindBookInfos();
                _bookIdLst.Clear();
                chkAll.Checked = false;
            }
            else
            {
                MessageBox.Show("移除失败");
            }
        }

        #endregion


    }
}

 优化

private void dgvUser_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    
    DataGridViewCell cell = dgvUser.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCell;
    if (cell.FormattedValue.ToString() == "新增")
    {
        Console.WriteLine(11111111111);
    }
    else if (cell.FormattedValue.ToString() == "修改")
    {
        Console.WriteLine(222222222);
    }
}

 

4、细节

using Library.BLL;
using Library.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Library.UI
{
    public partial class BookInfoFrm : Form
    {
        // 类型
        private readonly BookTypeBLL _bookTypeBLL = new BookTypeBLL();
        private List<BookTypeInfo> _bookTypes = new List<BookTypeInfo>();

        // 书架
        private readonly BookSelfBLL _bookSelfBLL = new BookSelfBLL();
        private List<BookSelfInfo> _bookSelfs = new List<BookSelfInfo>();

        // 图片 目录
        private string _imageDir;
        // 图片
        private string _bookimagePath;

        // 图书
        private readonly BookInfoBLL _bookInfoBLL = new BookInfoBLL();
        // 图书 Id
        private readonly int _bookId;

        // event
        public event Action ReloadBookInfoList;

        public BookInfoFrm()
        {
            InitializeComponent();
        }


        public BookInfoFrm(int bookId)
        {
            InitializeComponent();
            _bookId = bookId;   
        }

        private void BookInfoFrm_Load(object sender, EventArgs e)
        {
            // 显示 图书类型
            _bookTypes = _bookTypeBLL.GetBookTypeInfos();
            CboBookType.DataSource = _bookTypes;
            CboBookType.DisplayMember = "BookTypeName";
            CboBookType.ValueMember = "BookTypeId";

            // 显示 书架类型
            _bookSelfs = _bookSelfBLL.GetBookSelfInfos();
            ClbBookSelf.Items.Clear();
            ClbBookSelf.Items.AddRange(_bookSelfs.ToArray());

            // 图片文件
            _imageDir = Path.Combine(AppContext.BaseDirectory, "images");
            if (!Directory.Exists(_imageDir)) Directory.CreateDirectory(_imageDir);

            if (_bookId != 0) // 添加图书
            {
                BookInfo bookInfo = _bookInfoBLL.GetBookInfoByBookId(_bookId);
                if (bookInfo != null)
                {
                    // 编号
                    txtBookNum.Text = bookInfo.BookNo;
                    // 名称
                    txtBookName.Text = bookInfo.BookName;
                    // 类别
                    CboBookType.SelectedValue = bookInfo.BookTypeId;
                    // 价格
                    nudBookPrice.Value = (Decimal)bookInfo.Price;
                    // 数量
                    nudBookNum.Value = (Decimal)bookInfo.BookCount;
                    // 日期
                    dtpWarehouse.Value = bookInfo.CreateTime;
                    // 图片
                    ShowPicImage(bookInfo.BookImg);
                    // 选择书架
                    SetBookSelf(bookInfo.BookShelfId);
                    // 介绍
                    txtBookIntroduce.Text = bookInfo.BookRemark;
                }
            }
          

        }


        /// <summary>
        /// 书架信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClbBookSelf_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                //BookSelfInfo bookSelf = ClbBookSelf.SelectedItem as BookSelfInfo;
                BookSelfInfo bookSelf = ClbBookSelf.Items[e.Index] as BookSelfInfo;
                //Console.WriteLine($"新增:Id:{bookSelf.BookselfId}, Name:{bookSelf.BookselfName}");
                LstCheckedBookSelf.Items.Add(bookSelf);
            }
            else
            {
                BookSelfInfo bookSelf = ClbBookSelf.SelectedItem as BookSelfInfo;
                //Console.WriteLine($"删除:Id:{bookSelf.BookselfId}, Name:{bookSelf.BookselfName}");
                LstCheckedBookSelf.Items.Remove(bookSelf);
            }
        }

       


        /// <summary>
        /// 图片操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PicBookImg_Click(object sender, EventArgs e)
        {
            // 原图路径
            //string oldImagePath = PicBookImg.ImageLocation;
            // 替换图片
            OpenFileDialog ofd = new OpenFileDialog
            {
                InitialDirectory = @"D:\imgs",
                Title = "请选择图片",
                Multiselect = false,
                Filter = "图片文件|*.jpg|所有文件|*.*"
            };
            ofd.ShowDialog();
            // 处理路径
            string srcPath = ofd.FileName;
            PicBookImg.ImageLocation = srcPath;
            string fileName = Guid.NewGuid() + Path.GetExtension(srcPath);
            string targetPath = Path.Combine(_imageDir, fileName);
            File.Copy(srcPath, targetPath);
            PicBookImg.ImageLocation = targetPath;
            // 删除 目标路径不为空,源路径存在,删除源路径图片
            //if (!string.IsNullOrEmpty(targetPath)) 
            //{
            //    if (File.Exists(oldImagePath)) File.Delete(oldImagePath);
            //}
            // 数据库路径
            _bookimagePath = Path.Combine("images", fileName).Replace("\\", "/");
        }


        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSaveBookInfo_Click(object sender, EventArgs e)
        {
            BookInfo bookInfo = new BookInfo 
            {
                BookId = _bookId,
                BookNo = txtBookNum.Text.Trim(),
                BookName = txtBookName.Text.Trim(),
                BookTypeId = (int)CboBookType.SelectedValue,
                Price = (double)nudBookPrice.Value,
                BookCount = (int)nudBookNum.Value,
                CreateTime = dtpWarehouse.Value,
                BookImg = _bookimagePath,
                // 书架信息
                BookShelfId = GetBookSelfId(),
                BookRemark = txtBookIntroduce.Text.Trim()
            };
            bool success = _bookInfoBLL.StorageBookInfo(bookInfo);
            if (success)
            {
                MessageBox.Show("保存成功!!!");
                ReloadBookInfoList?.Invoke();
                this.Close();
            }
            else
            {
                MessageBox.Show("保存失败!!!");
            }
        }

        private void BtnCloseBookInfo_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 书架
        /// <summary>
        /// 设置书架信息
        /// </summary>
        /// <param name="bookSelfId"></param>
        private void SetBookSelf(string bookSelfId) 
        {
            // 获取id 列表
            List<int> idList = bookSelfId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(id => int.Parse(id)).ToList();
            // 选中 checkedListBox
            foreach (int item in idList)
            {
                for (int i = 0; i < ClbBookSelf.Items.Count; i++)
                {
                    if (ClbBookSelf.Items[i] is BookSelfInfo bookSelfInfo && bookSelfInfo.BookselfId == item)
                    {
                        ClbBookSelf.SetItemChecked(i, true);
                    }
                }
            }
        }

        /// <summary>
        /// 获取书架ids
        /// </summary>
        /// <returns></returns>
        private string GetBookSelfId() 
        {
            List<int> ids = new List<int>();
            foreach (BookSelfInfo item in LstCheckedBookSelf.Items)
            {
                ids.Add(item.BookselfId);
            }
            return string.Join(",", ids);
        }
        #endregion

        /// <summary>
        /// 展示图片
        /// </summary>
        /// <param name="bookInfo"></param>
        private void ShowPicImage(string bookPath) 
        {
            string bookImg = bookPath.Replace("/", "\\");
            string imagePath = Path.Combine(AppContext.BaseDirectory, bookImg);
            PicBookImg.ImageLocation = imagePath;
        }


    }
}

 

posted @ 2026-10-25 20:43  市丸银  阅读(8)  评论(0)    收藏  举报