分享

支持回车换行的DataGridView | CAD工具之家

 偷心无痕 2014-03-09

运行效果截图(原始)

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

/*
 * 文件:From1.cs
 * 说明:支持回车换行的DataGridView
 * 作者:Boitboy(游荡男孩)
 * 博客:http://www./
 * 支持回车换行的列有特定的要求
 * 本例中必须设定
 * 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;
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多