C# DataGridView控件用法大全

摘要:
通过将DataGridView对象的CurrentCell//Set(0,0)设置为当前单元格DataGridView1,可以更改当前单元格。CurrentCell=DataGridView1[0,0]//启用整行选择模式时,还可以通过CurrentCell设置所选行//如果DataGridView的DataSource绑定到DataView,还可以将DataView.AllowAdd属性设置为False以实现相同的效果。当新行DataGridView的AllowUserToAddRows属性为true时,即当允许用户附加新行时,DataGridView最后一行是新添加的行(*行)。使用DataGridViewRow。IsNewRow属性,以确定新追加的行。

动态添加新行

//方法一:
int index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[0].Value = "第1列单元格";
this.dataGridView1.Rows[index].Cells[1].Value = "第2列单元格";
//方法二:
DataGridViewRow row = new DataGridViewRow();
DataGridViewTextBoxCell textboxcell = new DataGridViewTextBoxCell();
textboxcell.Value = "abc";
row.Cells.Add(textboxcell);
DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell();
row.Cells.Add(comboxcell);
dataGridView1.Rows.Add(row);

方法二比方法一要复杂一些,但是在一些特殊场合非常实用,例如,要在新行中的某些单元格添加下拉框、按钮之类的控件时,该方法很有帮助。


设置行头和列头

// 改变第一列列头内容
DataGridView1.Columns[0].HeaderCell.Value = "第一列";
DataGridView1.Columns[0].HeaderText = "第一列";
// 改变第一行行头内容
DataGridView1.Rows[0].HeaderCell.Value = "第一行";
// 改变左上头部单元内容
DataGridView1.TopLeftHeaderCell.Value = "左上";

当前单元格

当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的 CurrentCell 属性取得。如果当前单元格不存在的时候,返回null

// 取得当前单元格内容
Console.WriteLine(DataGridView1.CurrentCell.Value);
// 取得当前单元格的列 Index
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
// 取得当前单元格的行 Index
Console.WriteLine(DataGridView1.CurrentCell.RowIndex);

另外,使用 DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddress.Y 列:DataGridView.CurrentCellAddress.X 。这对于避免取消共享行的共享非常有用。当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设定 DataGridView 的激活单元格。将 CurrentCell 设为 null 可以取消激活的单元格。

// 设定 (0, 0) 为当前单元格
DataGridView1.CurrentCell = DataGridView1[0, 0];
// 在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。
// 向下遍历
private void Down_Click(object sender, EventArgs e)
{
	int row = this.dataGridView1.CurrentRow.Index + 1;
	if (row > this.dataGridView1.RowCount - 1)
		row = 0;
	this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
// 向上遍历
private void Up_Click(object sender, EventArgs e)
{
	int row = this.dataGridView1.CurrentRow.Index - 1;
	if (row < 0)
		row = this.dataGridView1.RowCount - 1;
	this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}

注意:this.dataGridView 的索引器的参数是 [columnIndex, rowIndex] 或是 [columnName, rowIndex] 这与习惯不同。


设定单元格只读

// 设置 DataGridView1 为只读,所有单元格都不可编辑
DataGridView1.ReadOnly = true;
// 设置 DataGridView1 的第2列整列单元格为只读
DataGridView1.Columns[1].ReadOnly = true;
// 设置 DataGridView1 的第3行整行单元格为只读
DataGridView1.Rows[2].ReadOnly = true;
// 设置 DataGridView1 的[0,0]单元格为只读
DataGridView1[0, 0].ReadOnly = true;
// 以下方法用户不能手动编辑单元格的内容,但可通过 DataGridView.BeginEdit(True) 使单元格进入编辑模式
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;
// 通过 CellBeginEdit 事件来取消单元格的编辑
private void DataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
	DataGridView dgv = (DataGridView)sender;
	if (dgv.Columns[e.ColumnIndex].Name == "Column1" && !(bool)dgv["Column2", e.RowIndex].Value)
	{
		e.Cancel = true;// 取消编辑
	}
}

隐藏添加新行

// 设置用户不能手动给 DataGridView1 添加新行
DataGridView1.AllowUserToAddRows = false;
// 但是,可以通过代码 DataGridViewRowCollection.Add 追加新行。
// 如果 DataGridView 的 DataSource 绑定的是 DataView, 还可以通过设置 DataView.AllowAdd 属性为 False 来达到同样的效果。

判断新增行

DataGridView 的AllowUserToAddRows属性为True时也就是允许用户追加新行的场合下,DataGridView的最后一行就是新追加的行(*行)。
使用 DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的。通过 DataGridView.NewRowIndex 可以获取新行索引,没有新行时 NewRowIndex = -1


用户删除行

// DataGridView 默认允许用户删除行。如果设置 AllowUserToDeleteRows 属性为 False 时则被禁止
DataGridView1.AllowUserToDeleteRows = false;
// 通过 DataGridViewRowCollection.Remove 仍可删除。如果 DataGridView 绑定的是 DataView,通过 DataView.AllowDelete 也可删除。
// 用户删除行时,将触发 DataGridView.UserDeletingRow 事件
private void DataGridView1_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e)
{
	if (MessageBox.Show("确认要删除该行数据吗?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
	{
		e.Cancel = true;
	}
}

行列的隐藏和删除

// DataGridView1的第一列隐藏
DataGridView1.Columns[0].Visible = false;
// DataGridView1的第一行隐藏
DataGridView1.Rows[0].Visible = false;
// 列头隐藏
DataGridView1.ColumnHeadersVisible = false;
// 行头隐藏
DataGridView1.RowHeadersVisible = false;
// 删除名为"Column1"的列
DataGridView1.Columns.Remove("Column1");
// 删除第一行
DataGridView1.Rows.RemoveAt(0);
// 删除选中行
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
	if (!r.IsNewRow)
	{
		DataGridView1.Rows.Remove(r);
	}
}

禁止列行的Resize

// 禁止改变列宽
DataGridView1.AllowUserToResizeColumns = false;
// 禁止改变行高
DataGridView1.AllowUserToResizeRows = false;
// 但是可以通过 DataGridViewColumn.Width 或者 DataGridViewRow.Height 属性设定列宽和行高。
// 禁止改变第一列的列宽
DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;
// 禁止改变第一列的行高
DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;
// 当 Resizable 属性设为 DataGridViewTriState.NotSet 时, 实际上会默认以 DataGridView 的 AllowUserToResizeColumns 和 AllowUserToResizeRows 的属性值进行设定。比如:DataGridView.AllowUserToResizeColumns = False 且 Resizable 是 NoSet 设定时,Resizable = False 。判断 Resizable 是否是继承设定了 DataGridView 的 AllowUserToResizeColumns 和 AllowUserToResizeRows 的属性值,可以根据 State 属性判断。如果 State 属性含有 ResizableSet,那么说明没有继承设定。
// 第一列的最小列宽设定为 100
DataGridView1.Columns[0].MinimumWidth = 100;
// 第一行的最小行高设定为 50
DataGridView1.Rows[0].MinimumHeight = 50;
// 禁止用户改变列头的高度
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
// 设置用户改变行头的宽度
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;

自动调整列宽和行高

// 设定包括Header和所有单元格的列宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// 设定包括Header和所有单元格的行高自动调整
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
/*
DataGridViewAutoSizeColumnsMode 枚举
AllCells                    6   列宽调整到适合列中所有单元格(包括标头单元格)的内容。
AllCellsExceptHeader        4   列宽调整到适合列中除标头单元格以外所有单元格的内容。
ColumnHeader                2   列宽调整到适合列标头单元格的内容。
DisplayedCells              10  列宽调整到适合位于屏幕上当前显示的行中的列的所有单元格(包括标头单元格)的内容。
DisplayedCellsExceptHeader  8   列宽调整到适合位于屏幕上当前显示的行中的列的所有单元格(不包括标头单元格)的内容。
Fill                        16  列宽调整到使所有列宽精确填充控件的显示区域,要求使用水平滚动的目的只是保持列宽大于 MinimumWidth 属性值。 相对列宽由相对 FillWeight 属性值决定。
None                        1   列宽不会自动调整。
*/
dgv.Columns[0].MinimumWidth = 50; //第1列最小宽度为50像素
dgv.Columns[1].FillWeight = 22; //第2列的相对宽度为22%
// 第一列自动调整
DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; 
// AutoSizeMode 设定为 NotSet 时, 默认继承的是 DataGridView.AutoSizeColumnsMode 属性。
// 设定列头的宽度可以自由调整
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
// 设定行头的宽度可以自由调整
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
// 所有列宽自动调整一次
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
// 第一列的列宽自动调整一次
DataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnsMode.AllCells);
// 上面调用的 AutoResizeColumns 和 AutoResizeColumn 当指定的是DataGridViewAutoSizeColumnMode.AllCells 时参数可以省略。即:
DataGridView1.AutoResizeColumn(0) 和 DataGridView1.AutoResizeColumns()
// 所有行高自动调整一次
DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
// 第一行的行高自动调整一次
DataGridView1.AutoResizeRow(0, DataGridViewAutoSizeRowMode.AllCells);
// 当指定的是DataGridViewAutoSizeRowMode.AllCells 的时候,参数可以省略。即:
DataGridView1.AutoResizeRow (0) 和 DataGridView1.AutoResizeRows()
// 列头高度自动调整
DataGridView1.AutoResizeColumnHeadersHeight();
// 行头宽度自动调整
DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

关于性能:通过 AutoSizeColumnsMode 或者 AutoSizeRowsMode 属性所指定的单元格进行自动调整时,如果调整次数过于多那么将可能导致性能下降,尤其是在行和列数比较多的情况下。在这时用 DisplayedCells 代替 AllCells 能减少非所见的单元格的调整,从而提高性能。


冻结列或行

// 冻结左侧2列
DataGridView1.Columns[1].Frozen = true;
// 冻结前3行
DataGridView1.Rows[2].Frozen = true;

列顺序的调整

设定 DataGridView 的 AllowUserToOrderColumns 为 True 的时候, 用户可以自由调整列的顺序。当用户改变列的顺序的时候,其本身的 Index 不会改变,但是 DisplayIndex 改变了。你也可以通过程序改变 DisplayIndex 来改变列的顺序。 列顺序发生改变时会引发 ColumnDisplayIndexChanged 事件:

private void DataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
	Console.WriteLine("{0} 的位置改变到 {1} ", e.Column.Name, e.Column.DisplayIndex);
}

剪切板的操作

DataGridView.ClipboardCopyMode 属性被设定为 DataGridViewClipboardCopyMode.Disable 以外的情况时,[Ctrl + C] 按下时,被选择的单元格内容会拷贝到系统剪切板。格式有:
Text, UnicodeText,Html, CommaSeparatedValue。可以直接粘贴到 Excel 内。ClipboardCopyMode 还可以设定 Header部分是否拷贝:EnableAlwaysIncludeHeaderText 拷贝Header部分、EnableWithoutHeaderText 则不拷贝,默认是 EnableWithAutoHeaderText。

// 1) 编程方式实现剪切板的拷贝
Clipboard.SetDataObject(DataGridView1.GetClipboardContent())
// 2) 实现 DataGridView 的直接粘贴就比较难。「Ctrl + V」按下进行粘贴时,DataGridView 没有提供方法,只能自己实现。以下,是粘贴时简单的事例代码,将拷贝数据粘贴到以选择单元格开始的区域内。
if (DataGridView1.CurrentCell == null) return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;
// 获取剪切板的内容,并按行分割
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText)) return;
pasteText = pasteText.Replace(" ", " ");
pasteText = pasteText.Replace(' ', ' ');
pasteText.TrimEnd(new char[] { ' ' });
string[] lines = pasteText.Split(' ');
bool isHeader = true;
foreach (string line in lines)
{
	if (isHeader) // 是否是列头
	{
		isHeader = false;
		continue;
	}
	string[] vals = line.Split(' '); // 按 Tab 分割数据
	if (vals.Length - 1 != DataGridView1.ColumnCount)	// 判断列数是否统一
		throw new ApplicationException("粘贴的列数不正确。");
	DataGridViewRow row = DataGridView1.Rows[insertRowIndex];
	row.HeaderCell.Value = vals[0];  // 行头设定
	for (int i = 0; i < row.Cells.Count; i++)
	{
		row.Cells[i].Value = vals[i + 1];
	}
	insertRowIndex++;
}

单元格的ToolTip

DataGridView.ShowCellToolTips = True 的情况下, 单元格的 ToolTip 可以表示出来。对于单元格窄小,无法完全显示的单元格, ToolTip 可以显示必要的信息。

// 设定单元格的ToolTip内容
DataGridView1[0, 0].ToolTipText = "该单元格的内容不能修改";
// 设定列头的单元格的ToolTip内容
DataGridView1.Columns[0].ToolTipText = "该列只能输入数字";
// 设定行头的单元格的ToolTip内容
DataGridView1.Rows[0].HeaderCell.ToolTipText = "该行单元格内容不能修改";
// 在批量的单元格的 ToolTip 设定的时候,一个一个指定那么设定的效率比较低, 这时候可以利用 CellToolTipTextNeeded 事件。当单元格的 ToolTipText 变化的时候也会引发该事件。但是,当DataGridView的DataSource被指定且VirualMode = True的时候,该事件不会被引发。
private void DataGridView1_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
{
	e.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString();
}

右键菜单

DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell 有 ContextMenuStrip 属性。可以通过设定 ContextMenuStrip 对象来控制 DataGridView 的右键菜单的显示。 DataGridViewColumn 的 ContextMenuStrip 属性设定除列头以外的单元格右键菜单。 DataGridViewRow 的 ContextMenuStrip 属性设定除行头以外的单元格右键菜单。DataGridViewCell 的 ContextMenuStrip 属性设定指定单元格的右键菜单。

// DataGridView 的 ContextMenuStrip 设定
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
// 列的 ContextMenuStrip 设定
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
// 列头的 ContextMenuStrip 设定
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
// 行的 ContextMenuStrip 设定
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;
// 单元格的 ContextMenuStrip 设定
DataGridView1[0, 0].ContextMenuStrip = this.ContextMenuStrip4;
// 对于单元格上的右键菜单的设定,优先顺序是:Cell > Row > Column > DataGridView
// 利用 CellContextMenuStripNeeded 事件可以设定单元格的右键菜单,尤其是右键菜单需要根据单元格值的变化而变化的时候。比起使用循环遍历,使用该事件来设定右键菜单的效率更高。但是,在DataGridView使用了DataSource绑定而且是VirtualMode的时候,该事件将不被引发。
private void DataGridView1_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
	DataGridView dgv = (DataGridView)sender;
	if (e.RowIndex < 0)	// 列头的ContextMenuStrip设定
	{
		e.ContextMenuStrip = this.ContextMenuStrip1;
	}
	else if (e.ColumnIndex < 0)	// 行头的ContextMenuStrip设定
	{
		e.ContextMenuStrip = this.ContextMenuStrip2;
	}
	else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)	// 如果单元格值是整数时
	{
		e.ContextMenuStrip = this.ContextMenuStrip3;
	}
}

private void DataGridView1_RowContextMenuStripNeeded(object sender, DataGridViewRowContextMenuStripNeededEventArgs e)
{
	DataGridView dgv = (DataGridView)sender;
	object boolVal = dgv["Column1", e.RowIndex].Value;
	if (boolVal is bool && (bool)boolVal)	// 当"Column1"列是Bool型且为True时、设定其的ContextMenuStrip
	{
		e.ContextMenuStrip = this.ContextMenuStrip1;
	}
}

CellContextMenuStripNeeded 事件处理方法的参数中「e.ColumnIndex = -1」表示行头、「e.RowIndex = -1」表示列头。
RowContextMenuStripNeeded 则不存在「e.RowIndex = -1」的情况。


边框和网格线样式

  • 表格边框线样式:通过 DataGridView.BorderStyle 属性来设定。BorderStyle 枚举:FixedSingle(单线,默认)、Fixed3D、None。
  • 单元格边框线样式:通过 DataGridView.CellBorderStyle 属性来设定。另外,通过 DataGridView.ColumnHeadersBorderStyle 和 RowHeadersBorderStyle 属性可以修改 DataGridView 的头部的单元格边框线样式。属性设定值是 DataGridViewHeaderBorderStyle 枚举。
  • 单元格的边框颜色:通过 DataGridView.GridColor 属性来设定,默认是 ControlDarkDark,但是只有在 CellBorderStyle 被设定为 Single、SingleHorizontal、SingleVertical 时才能改变其边框线的颜色。同样,ColumnHeadersBorderStyle 以及 RowHeadersBorderStyle 只有在被设定为 Single 时,才能改变颜色。
  • 单元格的上下左右的边框线式样的单独设定:CellBorderStyle只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样时,需要用到DataGridView。

CellFormatting事件

通过CellFormatting事件,可以自定义单元格的表示值。(比如:值为Error的时候,单元格被设定为红色)下面的示例,将“Colmn1”列的值改为大写。

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
	DataGridView dgv = (DataGridView)sender;
	if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is string)
	{
		string str = e.Value.ToString();
		e.Value = str.ToUpper();
		e.FormattingApplied = true;
	}
}

CellFormatting事件的 DataGridViewCellFormattingEventArgs 对象的 Value 属性一开始保存着未被格式化的值。当 Value 属性被设定表示用的文本之后,把 FormattingApplied 属性做为 True,告知 DataGridView 文本已经格式化完毕。如果不这样做的话,DataGridView 会根据已经设定的 Format,NullValue,DataSourceNullValue,FormatProvider 属性会将 Value 属性会被重新格式化一遍。


CellParsing事件

通过 DataGridView.CellParsing 事件可以设定用户输入的值。下面的示例:当输入英文文本内容的时候,立即被改变为大写。

private void DataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
	DataGridView dgv = (DataGridView)sender;
	if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.DesiredType == typeof(string))
	{
		e.Value = e.Value.ToString().ToUpper();
		e.ParsingApplied = true;
	}
}

查找、添加、删除行

public class DataGridViewHelper
{
	/// <summary>
	/// DataGridView中查找指定列中的指定值,并选中该单元格
	/// </summary>
	/// <param name="dv">DataGridView控件</param>
	/// <param name="colnumber">找查的指定列</param>
	/// <param name="str">查找的指定值</param>
	/// <returns>如果有查找的值返回true,没有则返回false</returns>
	public bool Select(DataGridView dv, string colname, string str)
	{
		bool selected = false;
		int row = dv.Rows.Count;//得到总行数
		for (int i = 0; i < row; i++)//得到总行数并在之内循环
		{
			if (str == dv.Rows[i].Cells[colname].Value.ToString())//对比TexBox中的值是否与dataGridView中的值相同
			{
				dv.CurrentCell = dv[colname, i];//定位到相同的单元格
				selected = true;
				return selected;
			}
		}
		return selected;
	}
	/// <summary>
	/// 向DataGirdView中添加行,显示在第一行,并选中该行
	/// </summary>
	/// <param name="dv">DataGridView对向</param>
	/// <param name="colcount">总列数</param>
	/// <param name="colvalues">要添加的每列的值</param>
	public void AddRow(DataGridView dv, int colcount, params string[] colvalues)
	{
		DataGridViewRow dr = new DataGridViewRow();
		dr.CreateCells(dv);
		for (int i = 0; i < colcount; i++)
		{
			dr.Cells[i].Value = colvalues[i];
		}
		dv.Rows.Insert(0, dr);
		dv.CurrentCell = dv.Rows[0].Cells[0];
	}
	/// <summary>
	/// 删除DV中的指定行
	/// </summary>
	/// <param name="dv">DataGridView对向</param>
	/// <param name="colindex">要删除的指定行</param>
	public void ReMoveRow(DataGridView dv, int colindex)
	{
		dv.Rows.Remove(dv.Rows[colindex]);
		dv.ClearSelection();
	}
}

获取单元格内容

this.currentposition = this.dataGridView1.BindingContext [this.dataGridView1.DataSource, this.dataGridView1.DataMember].Position;
bookContent = this.database.dataSet.Tables[0].Rows [this.currentposition][21].ToString().Trim();

单元格颜色

dgv.Rows[0].Cells[0].Style.BackColor = Color.DarkOrange;
dgv.Rows[1].Cells[0].Style.ForeColor = Color.DarkRed;
//设置隔行颜色(方法1)
dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige //设置奇数行默认单元格样式
//设置隔行颜色(方法2)在数据绑定操作完成之后触发DataBindingComplete事件
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)    
{   
	if (this.dataGridView1.Rows.Count != 0)   
	{   
		for (int i = 0; i < this.dataGridView1.Rows.Count; i += 2)   
		{   
			this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Pink;   
		}   
	}   
}  

自定义列宽

this.dataGridView1.Columns[0].Width = 80;
this.dataGridView1.Columns[1].Width = 100;

Customize Cells and Columns in the Windows Forms DataGridView Control by Extending TheirBehavior and AppearanceHost Controls in Windows Forms DataGridView Cells
继承 DataGridViewTextBoxCell 类生成新的Cell类,然后再继承 DataGridViewColumn 生成新的Column类,并指定CellTemplate为新的Cell类。新生成的Column便可以增加到DataGridView中去。


自动适应列宽

DataGridView.AutoSizeColumns(DataGridViewAutoSizeColumnCriteria.HeaderAndDisplayedRows);
DataGridView.AutoSizeColumn(DataGridViewAutoSizeColumnCriteria.HeaderOnly, 2, false);
DataGridView.AutoSizeRow(DataGridViewAutoSizeRowCriteria.Columns, 2, false);
DataGridView.AutoSizeRows(DataGridViewAutoSizeRowCriteria.HeaderAndColumns, 0, dataGridView1.Rows.Count, false);

改变表格线条风格

this.dataGridView1.GridColor = Color.BlueViolet;
this.dataGridView1.BorderStyle = BorderStyle.Fixed3D;
this.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

列显示及顺序

customersDataGridView.Columns["CustomerID"].Visible = false;
customersDataGridView.Columns["ContactName"].DisplayIndex = 0;
customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;
customersDataGridView.Columns["City"].DisplayIndex = 2;

列中显示图像

Icon treeIcon = new Icon(this.GetType(), "tree.ico");
DataGridViewImageColumn iconColumn = new DataGridViewImageColumn ();
iconColumn.Image = treeIcon.ToBitmap();
iconColumn.Name = "Tree";
iconColumn.HeaderText = "Nice tree";
dataGridView1.Columns.Insert(2, iconColumn);

格式化显示内容

this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format = "d";
this.dataGridView1.DefaultCellStyle.NullValue = "no entry";
this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewWrapMode.Wrap;
this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

列冻结

在拖动横向滚动条时将指定列及以前的列固定不动
this.dataGridView1.Columns["AddToCartButton"].Frozen = true;


显示录入错误

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e) 
{	//显示录入时出现的错误信息
	if (e.Exception != null && e.Context == DataGridViewDataErrorContext.Commit)
	{
		MessageBox.Show("CustomerID value must be unique.");
	}
}

大数据量显示

采用Virtual Mode

移去自动生成的列

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = customerDataSet;
dataGridView1.Columns.Remove ("Fax");
// 或:
dataGridView1.Columns["CustomerID"].Visible = false;

自定义选择模式

this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
System.Windows.Forms.SendKeys.Send("^a"); //全选单元格的内容

编辑模式设置

自定义设定光标进入单元格是否编辑模式(编辑模式)
DataGridView Controlthis.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;


新行指定默认值

private void dataGridView1_DefaultValuesNeeded(object sender, System.Windows.Forms.DataGridViewRowEventArgs e)
{
	e.Row.Cells["Region"].Value = "WA";
	e.Row.Cells["City"].Value = "Redmond";
	e.Row.Cells["PostalCode"].Value = "98052-6399";
	e.Row.Cells["Region"].Value = "NA";
	e.Row.Cells["Country"].Value = "USA";
	e.Row.Cells["CustomerID"].Value = NewCustomerId();
}

数据验证

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
	if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
	{
		if (e.FormattedValue.ToString() == String.Empty)
		{
			dataGridView1.Rows[e.RowIndex].ErrorText ="Company Name must not be empty";
			e.Cancel = true; //终止事件链,单元格将保持编辑状态
		}
	}
}
//调用 dataGridView1.CancelEdit() 可以使单元格的内容回滚到修改前的值

数据提交到DataSet

DataSet ds = new DataSet("MyDataSet");
ds.Tables["t1"].Rows.Clear();
try
{
	for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
	{
		DataTable dt = ds.Tables[biaom.Trim()];
		DataRow myrow = ds.Tables[biaom.Trim()].NewRow();
		for (int j = 0; j < dataGridView1.Columns.Count; j++)
		{
			myrow[j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);
		}
		ds.Tables[biaom.Trim()].Rows.Add(myrow);
	}
}
catch (Exception)
{
	MessageBox.Show("输入类型错误!");
	return;
}

合并单元格

#region"合并单元格(多行多列)" 
//需要(行、列)合并的所有列标题名
List<String> colsHeaderText_V = new List<String>();
List<String> colsHeaderText_H = new List<String>();
 
private void InitFormatColumns()
{
    colsHeaderText_V.Add("PHONE1");
    colsHeaderText_V.Add("PHONE2");
 
    colsHeaderText_H.Add("IMAGEINDEX");
    colsHeaderText_H.Add("PARENTID");
    colsHeaderText_H.Add("DEPARTMENT");
    colsHeaderText_H.Add("LOCATION");
}
 
 
//绘制单元格
private void dataGridView1_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
    foreach (string fieldHeaderText in colsHeaderText_H)
    {
        //纵向合并
        if (e.ColumnIndex >= 0 && this.dataGridView1.Columns[e.ColumnIndex].HeaderText == fieldHeaderText && e.RowIndex >= 0)
        {
            using (
                Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
                backColorBrush = new SolidBrush(e.CellStyle.BackColor))
            {
                using (Pen gridLinePen = new Pen(gridBrush))
                {
                    // 擦除原单元格背景
                    e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
 
                    /* 绘制单元格相互间隔的区分线条,datagridview自己会处理左侧和上边缘的线条,因此只需绘制下边框和和右边框
                     DataGridView控件绘制单元格时,不绘制左边框和上边框,共用左单元格的右边框,上一单元格的下边框 */
 
                    //不是最后一行且单元格的值不为null
                    if (e.RowIndex < this.dataGridView1.RowCount - 1 && this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value != null)
                    {
                        //若与下一单元格值不同
                        if (e.Value.ToString() != this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString())
                        {
                            //下边缘的线
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1,
                            e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                            //绘制值
                            if (e.Value != null)
                            {
                                e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                                    Brushes.Crimson, e.CellBounds.X + 2,
                                    e.CellBounds.Y + 2, StringFormat.GenericDefault);
                            }
                        }
                        //若与下一单元格值相同 
                        else
                        {
                            //背景颜色
                            //e.CellStyle.BackColor = Color.LightPink;   //仅在CellFormatting方法中可用
                            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue;
                            this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Style.BackColor = Color.LightBlue;
                            //只读(以免双击单元格时显示值)
                            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true;
                            this.dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].ReadOnly = true;
                        }
                    }
                    //最后一行或单元格的值为null
                    else
                    {
                        //下边缘的线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1,
                            e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
 
                        //绘制值
                        if (e.Value != null)
                        {
                            e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                                Brushes.Crimson, e.CellBounds.X + 2,
                                e.CellBounds.Y + 2, StringFormat.GenericDefault);
                        }
                    }
 
                    ////左侧的线()
                    //e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                    //    e.CellBounds.Top, e.CellBounds.Left,
                    //    e.CellBounds.Bottom - 1);
 
                    //右侧的线
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                        e.CellBounds.Top, e.CellBounds.Right - 1,
                        e.CellBounds.Bottom - 1);
 
                    //设置处理事件完成(关键点),只有设置为ture,才能显示出想要的结果。
                    e.Handled = true;
                }
            }
        }
    }
 
    foreach (string fieldHeaderText in colsHeaderText_V)
    {
        //横向合并
        if (e.ColumnIndex >= 0 && this.dataGridView1.Columns[e.ColumnIndex].HeaderText == fieldHeaderText && e.RowIndex >= 0)
        {
            using (
                Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
                backColorBrush = new SolidBrush(e.CellStyle.BackColor))
            {
                using (Pen gridLinePen = new Pen(gridBrush))
                {
                    // 擦除原单元格背景
                    e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
 
                    /****** 绘制单元格相互间隔的区分线条,datagridview自己会处理左侧和上边缘的线条,因此只需绘制下边框和和右边框
                     DataGridView控件绘制单元格时,不绘制左边框和上边框,共用左单元格的右边框,上一单元格的下边框*****/
 
                    //不是最后一列且单元格的值不为null
                    if (e.ColumnIndex < this.dataGridView1.ColumnCount - 1 && this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value != null)
                    {
                        if (e.Value.ToString() != this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value.ToString())
                        {
                            //右侧的线
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top,
                                e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                            //绘制值
                            if (e.Value != null)
                            {
                                e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                                    Brushes.Crimson, e.CellBounds.X + 2,
                                    e.CellBounds.Y + 2, StringFormat.GenericDefault);
                            }
                        }
                        //若与下一单元格值相同 
                        else
                        {
                            //背景颜色
                            //e.CellStyle.BackColor = Color.LightPink;   //仅在CellFormatting方法中可用
                            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightPink;
                            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Style.BackColor = Color.LightPink;
                            //只读(以免双击单元格时显示值)
                            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = true;
                            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].ReadOnly = true;
                        }
                    }
                    else
                    {
                        //右侧的线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top,
                            e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
 
                        //绘制值
                        if (e.Value != null)
                        {
                            e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                                Brushes.Crimson, e.CellBounds.X + 2,
                                e.CellBounds.Y + 2, StringFormat.GenericDefault);
                        }
                    }
                    //下边缘的线
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1,
                                                e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                    e.Handled = true;
                }
            }
 
        }
    } 
}
#endregion

行号显示

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
	SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
	e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font,b,e.RowBounds.Location.X + 20,e.RowBounds.Location.Y + 4);
 }

免责声明:文章转载自《C# DataGridView控件用法大全》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇[vue问题解决]vue-cli项目引用mui.js报错Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be...强大的矩阵奇异值分解(SVD)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

devexpress实现单元格合并以及依据条件合并单元格

1、devexpress实现单元格合并非常的简单,只要设置属性【AllowCellMerge=True】就可以了,实现效果如下图: 2、但是在具体要求中并非需要所有的相同单元格都合并,可能需要其他的条件来控制合并。这个时候我们就需要在事件gridView1_CellMerge中来控制了。下图为根据最后一列判断是否合并单元格的效果图(其中第四列设置为不合并&...

easyExcel自动合并单元格

来源EasyExcel(根据条件动态合并单元格的重复数据) package com.ustcinfo.fn.comp.complain.util; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.e...

Java中使用poi导入、导出Excel

来自:http://blog.csdn.net/jerehedu/article/details/45195359 一、介绍    当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统、银行系统)。或者是:我们已经习惯用Excel打印。这样在我们实际的开发中,很多时候需要实现导入、...

Jquery实现鼠标双击Table单元格变成文本框,输入内容并更新到数据库

JS鼠标双击事件 onDblClick  <td width="10%" title="双击修改" ondblclick="ShowElement(this,<%#Eval("id") %></td>  这里的本人用绑定的值是传的当前行对应的ID号, function ShowElement(element, prod...

JS冒泡事件与处理

JavaSciprt事件中有两个很重要的特性:事件冒泡以及目标元素。 事件冒泡: 当一个元素上的事件被触发的时候,比如说鼠标点击了一个按钮,同样的事件将会在那个元素的所有祖先元素中被触发。这 一过程被称为事件冒泡;这个事件从原始元素开始一直冒泡到DOM树的最上层。 目标元素: 任何一个事件的目标元素都是最开始的那个元素,在我们的这个例子中也就是按钮,并且它...

gridControl通过设置条件,改变单元格颜色

我现在用gridControl,需要改变单元格颜色。(标准值-偏差负)<=检测值<=(检测值+偏差正)之外,检测值就显示红色,或者背景设置成红色。用了RowCellStyle和CustomDrawCell都无法达到效果。而且出现程序卡死的情况。网上有人说gridcontrol有Apperance-----Format conditions 但是...