运行效果截图(原始)
运行效果截图(按下回车键)
/*
* 文件: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;
}
}
}
下载:https://files.cnblogs.com/boitboy/Boitboy.DataGridViewEx.rar