感谢您阅读我的博客,如果您现在工作、学习累了或者疲惫了,不妨聆听一下音乐,它能够减轻你的疲劳,还能够带给您一种舒适愉悦的心情。如果您认为这篇文章还不错或者有所收获,您可以在页面 右侧和底部 扫描二维码 打赏我,您的鼓励是我继续写作、分享的最大动力!

WinForm里DataGridView默认样式设置(添加序号列)

 

 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ConsoleExtClass;
using DataGridViewDemo01.Helpers;
using MessageBoxer;

namespace DataGridViewDemo01
{
    /// <summary>
    ///     WinForm里DataGridView默认样式设置(添加序号列)
    ///     LDH @ 2021-10-22
    /// </summary>
    public partial class FrmMain : Form
    {
        #region Global Variables

        /// <summary>
        ///     创建学生列表
        /// </summary>
        private readonly List<Student> _list = new List<Student>();

        #endregion

        #region Constructor

        public FrmMain()
        {
            InitializeComponent();
        }

        #endregion

        #region My Methods

        /// <summary>
        ///     绑定学生列表
        /// </summary>
        private void BindStudents()
        {
            dgvStudents.DataSource = null; // 清空绑定
            dgvStudents.DataSource = _list; // 指定数据源

            dgvStudents.AllowUserToResizeRows = false; // 禁止用户改变DataGridView所有行的行高  
            dgvStudents.AutoGenerateColumns = false; // 禁止自动生成列

            #region 【LDH珍藏的样式V2021.10】

            // 设置样式(最爱) 
            DataGridViewHelperV2.SetStyleForDataGridView(
                dgvStudents,
                Color.FromArgb(192, 139, 165),
                Color.White,
                Color.FromArgb(213, 186, 199),
                Color.FromArgb(249, 250, 249),
                Color.FromArgb(238, 229, 234),
                false,
                Color.GhostWhite,
                true);

            #endregion
        }

        /// <summary>
        ///     设置控件
        /// </summary>
        private void SetControls()
        {
            MaximizeBox = false; // 禁用最大化按钮
            AutoSizeMode = AutoSizeMode.GrowAndShrink; // 不让窗体右下角拖拽

            dgvStudents.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // DataGridView 整行选取
            dgvStudents.AllowUserToAddRows = false; // 不向用户显示添加行的选项
            dgvStudents.AllowUserToResizeRows = false; // 禁止用户改变DataGridView所有行的行高  
            dgvStudents.AutoGenerateColumns = false; // 禁止自动生成列

            // 添加序号(最左侧列)
            //dgvStudents.RowsAdded += DgvStudents_RowsAdded;
            //dgvStudents.RowsRemoved += DgvStudents_RowsRemoved;
        }

        #endregion

        #region Form Events

        /// <summary>
        ///     添加学生
        /// </summary>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            var stu = new Student
            {
                StuNo = txtStuNo.Text,
                StuName = txtStuName.Text,
                StuSex = cboStuSex.Text,
                StuAge = Convert.ToInt32(nupStuAge.Value)
            };

            _list.Add(stu);

            BindStudents();

            ConsoleExt.InfoLine("添加成功!");
            MessageTip.ShowOk("添加成功!");
        }

        /// <summary>
        ///     删除行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 共选中的行数
            var selectedRowCount = dgvStudents.SelectedRows.Count;
            if (selectedRowCount > 0)
            {
                var dr = ShowMessage.GetUserYesOrNo("您是否要删除选择的记录呢?", "温馨提示");
                if (dr == DialogResult.Yes)
                {
                    // 遍历所有选中的行
                    for (var i = 0; i < selectedRowCount; i++)
                    {
                        var index = dgvStudents.SelectedRows[i].Index;
                        _list.RemoveAt(index);
                    }

                    // 重新绑定
                    BindStudents();
                    MessageTip.ShowOk("删除成功!");
                    ConsoleExt.InfoLine("删除成功!");
                }
                else
                {
                    MessageTip.ShowOk("您取消了删除操作!");
                    ConsoleExt.WarnLine("您取消了删除操作!");
                }
            }
            else
            {
                tipDelete.Show("请先选择您要删除的行!", btnDelete, 0, -btnDelete.Height, 5000);
                ConsoleExt.ErrorLine("请先选择您要删除的行!");
            }
        }

        /// <summary>
        ///     窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            SetControls();
        }

        /// <summary>
        ///     窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            var dr = ShowMessage.GetUserYesOrNo("您确定现在退出系统吗?", "温馨提示");
            if (dr == DialogResult.Yes)
                Environment.Exit(0);
            else
                e.Cancel = true;
        }

        #region 【添加序号(最左侧列)】

        private void DgvStudents_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            var dgv = (DataGridView)sender;
            if (dgv.Rows.Count != 0)
            {
                for (var i = 0; i < e.RowCount; i++)
                {
                    dgv.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dgv.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
                }

                for (var i = e.RowIndex + e.RowCount; i < dgv.Rows.Count; i++)
                {
                    dgv.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dgv.Rows[i].HeaderCell.Value = (i + 1).ToString();
                }
            }
        }

        private void DgvStudents_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            var dgv = (DataGridView)sender;
            for (var i = 0; i < e.RowCount; i++)
            {
                dgv.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgv.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
            }

            for (var i = e.RowIndex + e.RowCount; i < dgv.Rows.Count; i++)
            {
                dgv.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgv.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
        }

        #endregion

        #endregion
    }
}
namespace DataGridViewDemo01
{
    public class Student
    {
        public string StuNo { get; set; }
        public string StuName { get; set; }
        public string StuSex { get; set; }
        public int StuAge { get; set; }
    }
}

 

posted @ 2021-10-22 16:49  Love In Winter  阅读(1268)  评论(0编辑  收藏  举报
作者: LifeDecidesHappiness
出处: http://www.cnblogs.com/LifeDecidesHappiness/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,否则保留追究法律责任的权利,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址 2468881301@qq.com  联系我,非常感谢。
踏实做一个为人民服务的搬运工!
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能,您的支持和鼓励是我继续写作、分享的最大动力!

点击关注不迷路,让我带你上高速!