ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

记录一个自己写的表格控件类(继承自DataGridView)

2022-05-17 22:36:32  阅读:167  来源: 互联网

标签:控件 Rows 表格 index DataGridView cell str new row


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 表格控件类
{
    /// <summary>
    /// 自定义表格控件
    /// </summary>
    class CustomDataGridView : DataGridView
    {
        private ContextMenuStrip contextMenuStrip;//右键菜单(复制、粘贴)

        public CustomDataGridView()
        {
            this.AllowUserToAddRows = false;//关闭添加行
            this.AllowUserToDeleteRows = false;//关闭删除行
            this.AllowUserToOrderColumns = false;//关闭手动列重新放置
            this.AllowUserToResizeColumns = false;//关闭调整列宽
            this.AllowUserToAddRows = false; //关闭调整行高
            this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;//可见列自动调节大小的模式
            this.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;//可见行自动调节大小的模式
            this.BackgroundColor = Color.White;//背景色设置为白色
            this.BorderStyle = BorderStyle.FixedSingle;//边框样式
            this.CellBorderStyle = DataGridViewCellBorderStyle.Single;//单元格Cell的边框样式
            this.ClipboardCopyMode = DataGridViewClipboardCopyMode.Disable;//关闭单元格复制(事件中重写)
            this.ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
            {
                Alignment = DataGridViewContentAlignment.MiddleCenter,
                Font = new Font("微软雅黑", 9)
            };
            this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;//自动调节列标题高度
            this.ColumnHeadersVisible = true;//显示列标题
            //this.ReadOnly = true;
            this.RowHeadersDefaultCellStyle = new DataGridViewCellStyle//行标题居中
            {
                Alignment = DataGridViewContentAlignment.MiddleCenter,
                Font = new Font("微软雅黑", 9)

            };
            this.RowHeadersVisible = true;//显示行标题
            this.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

            this.RowsDefaultCellStyle = new DataGridViewCellStyle
            {
                Alignment = DataGridViewContentAlignment.MiddleLeft,
                Font = new Font("微软雅黑", 9)
            };
            this.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;//单元格选择模式
            //右键控件绑定
            contextMenuStrip = new ContextMenuStrip
            {
                Name = "cms1"
            };
            ToolStripItem Copy = contextMenuStrip.Items.Add("复制(Ctrl+C)");//右键复制控件
            ToolStripItem Paste =  contextMenuStrip.Items.Add("粘贴(Ctrl+V)");//右键粘贴控件
            Copy.Click += Copy_Click;
            Paste.Click += Paste_Click;
            //this.ContextMenuStrip = contextMenuStrip;
            //事件
            this.RowsAdded += DataGridView_RowsAdded;//侧边栏序号生成
            this.RowsRemoved += DataGridView_RowsRemoved;//侧边栏序号生成
            this.MouseUp += DataGridView_MouseUp;
            this.KeyDown += DataGridView_KeyDown;


            



            for (int i = 1; i < 9; i++)
            {
                //添加列
                int index = this.Columns.Add("aaa" + i.ToString(), "asasasaas");
                this.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                this.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            for (int i = 0; i < 10; i++)
            {
                int index = this.Rows.Add();

                int a = 1;
                foreach (DataGridViewCell cell in this.Rows[index].Cells)
                {
                    cell.Value = a.ToString();
                    a++;
                }
            }
        }
        /// <summary>
        /// ctrl+C、ctrl+V
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_KeyDown(object sender, KeyEventArgs e)//ctrl+C、ctrl+V
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                Copy_Click(new object(), new EventArgs());
            }
            if (e.Control && e.KeyCode == Keys.V)
            {
                Paste_Click(new object(), new EventArgs());
            }
        }
        /// <summary>
        /// 右键复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Copy_Click(object sender, EventArgs e)//右键复制
        {
            if (this.SelectedCells.Count > 0)
            {
                string copy_str = "";
                foreach (DataGridViewRow datagridviewrow in this.Rows)
                {
                    string cell_str = "";
                    foreach (DataGridViewCell cell in datagridviewrow.Cells)
                    {
                        foreach (DataGridViewCell cell_s in this.SelectedCells)
                        {
                            if (cell == cell_s)
                            {
                                cell_str = cell_str + cell.Value.ToString() + "    ";
                            }
                        }
                        //消除最后一个tab
                    }
                    if (cell_str != "")
                    {
                        cell_str = cell_str.Substring(0, cell_str.Length - 1);
                        copy_str = copy_str + cell_str + "\r\n";
                    }
                }
                Clipboard.SetText(copy_str);
            }
        }
        /// <summary>
        /// 右键粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Paste_Click(object sender, EventArgs e)//右键粘贴
        {
            foreach (DataGridViewCell cell in dataGridViewCells)
            {
                if (cell.Displayed)
                {
                    cell.ContextMenuStrip = null;
                }
            }
            List<DataGridViewCell> selectcells = new List<DataGridViewCell>();//粘贴成功的cell集合
            string context = Clipboard.GetText();
            List<List<string>> contexts = StrToList(context);
            List<int> row_indexs = new List<int>();
            List<int> Column_indexs = new List<int>();
            foreach (DataGridViewCell cell in this.SelectedCells)
            {
                row_indexs.Add(cell.RowIndex);
                Column_indexs.Add(cell.ColumnIndex);
            }
            row_indexs.Sort();
            Column_indexs.Sort();

            int star_row_index = row_indexs[0];
            foreach (List<string> str_rows in contexts)
            {
                int star_Column_index = Column_indexs[0];
                foreach (string str_cell in str_rows)
                {
                    try
                    {
                        if (this.Rows[star_row_index].Cells[star_Column_index].ReadOnly == false)
                        {
                            this.Rows[star_row_index].Cells[star_Column_index].Value = str_cell;
                            selectcells.Add(this.Rows[star_row_index].Cells[star_Column_index]);
                        }
                        else
                        {
                            this.Rows[star_row_index].Cells[star_Column_index].Selected = false;
                        }
                    }
                    catch (Exception)
                    {
                    }
                    star_Column_index++;
                }
                star_row_index++;
            }
            foreach (DataGridViewCell cell in selectcells)
            {
                cell.Selected = true;
                cell.ContextMenuStrip = contextMenuStrip;
                dataGridViewCells.Add(cell);
            }
        }
        /// <summary>
        /// 当前选择CELL的备份列表
        /// </summary>
        private List<DataGridViewCell> dataGridViewCells = new List<DataGridViewCell>();
        /// <summary>
        /// 鼠标单击框选单元格事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_MouseUp(object sender, MouseEventArgs e)//鼠标单击框选单元格事件
        {
            
            if (e.Button == MouseButtons.Left)
            {
                foreach (DataGridViewCell cell in dataGridViewCells)
                {
                    if (cell.Displayed)
                    {
                        cell.ContextMenuStrip = null;
                    }
                }
                if (this.SelectedCells.Count > 0)
                {
                    foreach (DataGridViewCell cell in this.SelectedCells)
                    {
                        cell.ContextMenuStrip = contextMenuStrip;
                        dataGridViewCells.Add(cell);
                    }
                }
            }
        }
        /// <summary>
        /// 侧边栏序号生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)//侧边栏序号生成
        {
            if (this.Rows.Count > 0)
            {
                for (int i = 0; i < e.RowCount; i++)
                {
                    this.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    this.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
                }

                for (int i = e.RowIndex + e.RowCount; i < this.Rows.Count; i++)
                {
                    this.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    this.Rows[i].HeaderCell.Value = (i + 1).ToString();
                }
            }
        }
        /// <summary>
        /// 侧边栏序号生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)//侧边栏序号生成
        {
            if (this.Rows.Count > 0)
            {
                for (int i = 0; i < e.RowCount; i++)
                {
                    if (e.RowIndex + i < this.Rows.Count)
                    {
                        this.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        this.Rows[e.RowIndex + i].HeaderCell.Value =(e.RowIndex + i + 1).ToString();
                    }
                }

                for (int i = e.RowIndex + e.RowCount; i < this.Rows.Count; i++)
                {
                    if (i < this.Rows.Count)
                    {
                        this.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        this.Rows[i].HeaderCell.Value =(i + 1).ToString();
                    }
                }
            }
        }
        /// <summary>
        /// 粘贴板数据整理成表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private List<List<string>> StrToList(string context)
        {
            List<List<string>> contexts = new List<List<string>>();
            int StarIndex = 0;
            while (context.IndexOf("\r\n", StarIndex) != -1)
            {
                int EbdIndex = context.IndexOf("\r\n", StarIndex);
                string str_row = context.Substring(StarIndex, EbdIndex - StarIndex);
                int str_row_StarIndex = 0;
                List<string> cells = new List<string>();
                while (str_row.IndexOf("    ", str_row_StarIndex) != -1)
                {
                    int str_row_EbdIndex = str_row.IndexOf("    ", str_row_StarIndex);
                    string cell = str_row.Substring(str_row_StarIndex, str_row_EbdIndex - str_row_StarIndex);
                    cells.Add(cell);
                    str_row_StarIndex = str_row_EbdIndex + 1;
                    if (str_row_StarIndex > str_row.Length - 1)
                    {
                        break;
                    }
                }
                cells.Add(str_row.Substring(str_row_StarIndex, str_row.Length - str_row_StarIndex));
                contexts.Add(cells);
                StarIndex = EbdIndex + 2;
                if (StarIndex > context.Length - 1)
                {
                    break;
                }
            }
            return contexts;
        }
    }
}
View Code

 

标签:控件,Rows,表格,index,DataGridView,cell,str,new,row
来源: https://www.cnblogs.com/zhemingxiangyixiu/p/16282645.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有