标签:c#
默认我们的DataGridView cell是没有边框的,无伦是正常状态还是编辑状态,因为系统把TextBox的BorderStyle值改成了None,所以这里首先要把BorderStyle值改回来,那至于是FixedSingle还是Fixed3D,就得看你自己需要了,我这里改成了FixedSingle,方便绘制
主要是继承 DataGridViewTextBoxCell 类,需要在这里改点东西代码如下:
public class DataGridViewTextBoxEditCell : DataGridViewTextBoxCell { public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle) { base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); TextBox textBox = this.DataGridView.EditingControl as TextBox; if (textBox != null) { textBox.BorderStyle = BorderStyle.FixedSingle;//改回边框 } } protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); //绘制边框 Rectangle cellBounds1 = new Rectangle(cellBounds.X + 2, cellBounds.Y + 1, cellBounds.Width - 4, cellBounds.Height - 3); graphics.DrawRectangle(new Pen(SystemColors.WindowFrame), cellBounds1); } } public class DataGridViewTextBoxEditColumn : DataGridViewColumn { public DataGridViewTextBoxEditColumn() : base(new DataGridViewTextBoxEditCell()) { } public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { // Ensure that the cell used for the template is a CalendarCell. if (value != null && !value.GetType().IsAssignableFrom(typeof(DataGridViewTextBoxEditCell))) { throw new InvalidCastException("Must be a CalendarCell"); } base.CellTemplate = value; } } } 应用: private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("name"); dt.Columns.Add("name1"); DataGridViewTextBoxEditColumn dataGridViewColumn = new DataGridViewTextBoxEditColumn(); dataGridViewColumn.HeaderText = "columns"; dataGridViewColumn.DataPropertyName = "name"; this.dataGridView1.Columns.Add(dataGridViewColumn); DataGridViewTextBoxEditColumn dataGridViewColumn1 = new DataGridViewTextBoxEditColumn(); dataGridViewColumn1.HeaderText = "columns"; dataGridViewColumn1.DataPropertyName = "name1"; this.dataGridView1.Columns.Add(dataGridViewColumn1); this.dataGridView1.AutoGenerateColumns = false; this.dataGridView1.DataSource = dt; } 应该还有更多好的办法,希望大家能批评改正
标签:c#
原文地址:http://mjb40.blog.51cto.com/3751139/1914794