您的位置:首页 > 编程语言 > C#

C# datagridview 实现单元格内容进行回车换行而不是换另一行数据

2017-08-12 14:58 2061 查看
自带的换行是shift+enter但客户偏偏想要enter换行,无耐百度了好久才搜到这一篇文章。稍加改动就可实现自己的功能



运行效果截图(原始)



运行效果截图(按下回车键)

/*

 * 文件:From1.cs

 * 说明:支持回车换行的DataGridView

 * 作者:Boitboy(游荡男孩)

 * 博客:http://boitboy.cnblogs.com/

 * 支持回车换行的列有特定的要求

 * 本例中必须设定

 * dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;

 * this.Column2.DefaultCellStyle = dataGridViewCellStyle2;

 */

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace Boitboy.DataGridViewEx

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            dataGridView1.Rows.Add("测试行1", "不支持回车换行的单元格", "");

            dataGridView1.Rows[0].Height = 25;

            dataGridView1.Rows.Add("测试行2", "支持回车换行的单元格", "");

            dataGridView1.Rows[1].Height = 75;

            //属性值

            dataGridView1.Rows[1].Cells[1].Style.Tag = true;

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)

        {

            if (keyData != Keys.Enter)

            {

                //继续原来base.ProcessCmdKey中的处理 

                return base.ProcessCmdKey(ref msg, keyData);

            }

            if (!this.dataGridView1.IsCurrentCellInEditMode)   //如果当前单元格处于编辑模式

            {

                //继续原来base.ProcessCmdKey中的处理 

                return base.ProcessCmdKey(ref msg, keyData);

            }

            if (this.dataGridView1.CurrentCell.Style.Tag == null ||

                !(this.dataGridView1.CurrentCell.Style.Tag is bool))

            {

                return base.ProcessCmdKey(ref msg, keyData);

            }

            TextBox textBox = this.dataGridView1.EditingControl as TextBox;

            int nStart = textBox.SelectionStart;//得到当前光标的位置

            string text = textBox.Text;

            if (nStart < 0 || nStart > text.Length)

                return false;

            //光标签名的字

            string text1 = "";

            if (nStart > 0)

            {

                text1 = text.Substring(0, nStart);

            }

            //光标后面的字

            string text2 = "";

            if (nStart < text.Length)

            {

                text2 = text.Substring(nStart, text.Length - nStart);

            }

            text = text1 + "\r\n" + text2;

            textBox.Text = text;

            this.dataGridView1.CurrentCell.Value = text;

            textBox.Select(nStart + 2, 0);

            return true;

        }

    }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息