DataGridView 使用精华
DataGridView控件用法合集
1. 当前的单元格属性取得、变更
[C#]
//显示当前单元格的值
Console.WriteLine(DataGridView1.CurrentCell.Value);
//显示当前单元格的列索引
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
//显示当前单元格的行索引
Console.WriteLine(DataGridView1.CurrentCell.RowIndex);
//(0,0)为现在的单元格
DataGridView1.CurrentCell = DataGridView1[0, 0];
2. 编辑属性
全部单元格编辑属性
[C#]
//读取DataGridView 1的单元格
DataGridView1.ReadOnly = true;
指定行列单元格编辑属性
[C#]
/读DataGridView 1的第二列
DataGridView1.Columns[1].ReadOnly = true;
//使DataGridView1的第三行为只读
DataGridView1.Rows[2].ReadOnly = true;
//读取DataGridView 1的(0,0)的单元格
DataGridView1[0, 0].ReadOnly = true;
根据条件判断单元格的编辑属性
下例中column2的值是True的时候,Column1设为可编辑
[C#]
//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;
}}
3. 最下面一列新追加行非表示
3.DataGridView最下面一列新追加行非表示
[C#]
//用户不能将新的行添加到DataGridView 1
DataGridView1.AllowUserToAddRows = false;
4. 判断当前选中行是否为新追加的行
[C#]
if (DataGridView1.CurrentRow.IsNewRow)
Console.WriteLine("有现在的单元格的行是新的行");
else
Console.WriteLine("现在的电池有行,新行吗。");
5.删除行可否设定
[C#]
//DataGridView一行用户删除不了的
DataGridView1.AllowUserToDeleteRows = false;
根据条件判断当前行是否要删除
[C#]
//DataGridView 1的UserDeleting Rime事件韩剧
private void DataGridView1_UserDeletingRow(
object sender, DataGridViewRowCancelEventArgs e)
{
//删除或确认用户
if (MessageBox.Show("您要删除这一列吗?",
"确认删除",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question) != DialogResult.OK)
{
e.Cancel = true;
}
}
6. 行列不表示和删除
行列不表示
[C#]
//隐藏包含DataGridView1的列
DataGridView1.Columns[0].Visible = false;
//非显示DataGridView 1的行
DataGridView1.Rows[0].Visible = false;
行列表头部分不表示
[C#]
//隐藏列标题
DataGridView1.ColumnHeadersVisible = false;
//非显示行页眉
DataGridView1.RowHeadersVisible = false;
指定行列删除
[C#]
//"删除列1
DataGridView1.Columns.Remove("Column1");
//删除开始列
DataGridView1.Columns.RemoveAt(0);
//删除最初的行
DataGridView1.Rows.RemoveAt(0);
选择的行列删除(多行列)
[C#]
//删除所有在DataGridView 1所选择的行
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
if (!r.IsNewRow)
{
DataGridView1.Rows.Remove(r);
}
}
7. 行列宽度高度设置为不能编辑
[C#]
//用户不能改变DataGridView 1的列的宽度
DataGridView1.AllowUserToResizeColumns = false;
//防止用户更改DataGridView1行的高度
DataGridView1.AllowUserToResizeRows = false;
指定行列宽度高度设置为不能编辑
[C#]
//让用户无法改变DataGridView 1的列的宽度
DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;
//防止用户更改DataGridView1的第一行的高度
DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;
列幅行高最小值设定
[C#]
//以最开始的列的宽度最小为100像素
DataGridView1.Columns[0].MinimumWidth = 100;
//以第一个行的高度最小为50个像素
DataGridView1.Rows[0].MinimumHeight = 50;
行列表头部分行高列幅设置为不能编辑
[C#]
//阻止更改列标题的高度
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
//调整行页眉的宽度
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.EnableResizing;
8. 行高列幅自动调整
[C#]
//根据页眉和所有单元格的内容,自动调整列的宽度
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
//根据标题和所有单元格内容自动调整行高度
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
表头部分行高列幅自动调整
[C#]
//自动调整列标题的高度
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.AutoSize;
//自动调整行标题的宽度
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
指定列自动调整
[C#]
//自动调整前列的宽度
DataGridView1.Columns[0].AutoSizeMode =
DataGridViewAutoSizeColumnMode.DisplayedCells;
9. 指定行列冻结
列冻结(当前列以及左侧做所有列)
[C#]
//固定DataGridView1的左侧两列
DataGridView1.Columns[1].Frozen = true;
行冻结(当前行以及上部所有行)
[C#]
//固定DataGridView 1的上部2行
DataGridView1.Rows[2].Frozen = true;
指定单元格冻结(单元格所在行上部分所有行,列左侧所有列)
[C#]
DataGridView1[0, 0]. Frozen = true;
10. 列顺序变更可否设定
[C#]
//用户可以改变DataGridView 1的列的位置
DataGridView1.AllowUserToOrderColumns = true;
但是如果列冻结的情况下,冻结的部分不能变更到非冻结的部分。
变更后列位置取得
[C#]
//列“Column1”的当前位置
Console.WriteLine(DataGridView1.Columns["Column1"].DisplayIndex);
//排在前面的“Column1”
DataGridView1.Columns["Column1"].DisplayIndex = 0;
11. 行复数选择
复数行选择不可
[C#]
//在DataGridView 1中不选择多个单元格,行,列
DataGridView1.MultiSelect = false;
单元格选择的时候默认为选择整行
[C#]
//选择单元格并选择整个行
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
12. 选择的行、列、单元格取得
[C#]
//显示选择的单元格
Console.WriteLine("选择的单元格");
foreach (DataGridViewCell c in DataGridView1.SelectedCells)
{
Console.WriteLine("{0}, {1}", c.ColumnIndex, c.RowIndex);
}
//显示选择的行
Console.WriteLine("被选择的行");
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
Console.WriteLine(r.Index);
}
//显示选择的列
Console.WriteLine("选择的列");
foreach (DataGridViewColumn c in DataGridView1.SelectedColumns)
{
Console.WriteLine(c.Index);
}
指定行、列、单元格取得
[C#]
//选择(0,0)的单元格
DataGridView1[0, 0].Selected = true;
//选择索引1中的行
DataGridView1.Rows[1].Selected = true;
//选择索引2中的列
DataGridView1.Columns[2].Selected = true;
13. 指定单元格是否表示
[C#]
if (!DataGridView1[0, 0].Displayed && DataGridView1[0, 0].Visible)
{
DataGridView1.CurrentCell = DataGridView1[0, 0];
}
14. 表头部单元格取得
[C#]
//改变DataGridView 1的列的文本
DataGridView1.Columns[0].HeaderCell.Value = "开始列";
//改变DataGridView 1的行的文本
DataGridView1.Rows[0].HeaderCell.Value = "第一行";
//更改DataGridView1左上角单元格中的文本
DataGridView1.TopLeftHeaderCell.Value = "左上";
15. 表头部单元格文字列设定
更改列Header表示文字列
[C#]
//改变DataGridView 1的列的文本
DataGridView1.Columns[0].HeaderText = "开始列";
更改行Header表示文字列
[C#]
//在DataGridView1的行标题中显示行号
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
DataGridView1.Rows[i].HeaderCell.Value = i.ToString();
}
//自动调节行页眉的宽度
DataGridView1.AutoResizeRowHeadersWidth(
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
最左上Header单元格文字列
[C#]
//在左上角的标题单元格中显示“/”
DataGridView1.TopLeftHeaderCell.Value = "/";
16. 选择的部分拷贝至剪贴板
拷贝模式设定
[C#]
//不复制标题
DataGridView1.ClipboardCopyMode =
DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
选中部分拷贝
[C#]
//将选定的单元格复制到剪贴板
Clipboard.SetDataObject(DataGridView1.GetClipboardContent());
17. 粘贴
[C#]
//从现在的单元格的行到下
if (DataGridView1.CurrentCell == null)
return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;
//取得剪切板的内容,用行分开
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
pasteText = pasteText.Replace("\r\n", "\n");
pasteText = pasteText.Replace('\r', '\n');
pasteText.TrimEnd(new char[] { '\n' });
string[] lines = pasteText.Split('\n');
bool isHeader = true;
foreach (string line in lines)
{
//列页眉的话就飞
if (isHeader)
{
isHeader = false;
continue;
}
//分割标签
string[] vals = line.Split('\t');
//调查列数合适
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++;
}
18. 单元格上ToolTip表示设定(鼠标移动到相应单元格上时,弹出说明信息)
[C#]
//设置在单元格中显示的ToolTip
DataGridView1[0, 0].ToolTipText = "このセルは変更できません";
//设置在列页眉上显示的ToolTip
DataGridView1.Columns[0].ToolTipText = "この列には数字を入力できます";
//设置在行页眉上显示的ToolTip
DataGridView1.Rows[0].HeaderCell.ToolTipText = "この行のセルは変更できません";
[C#]
//CellToolTipTextNeeded事件处理程序
private void DataGridView1_CellToolTipTextNeeded(object sender,
DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = e.ColumnIndex.ToString() + ", " + e.RowIndex.ToString();
}
19. 中的ContextMenuStrip属性
[C#]
//设定DataGridView的控制程序
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
//设置列中的LayerMenuBarp
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
//设置列页眉的控制程序
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
//设置行的换行和条带p
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;
//设定单元格的控制程序
DataGridView1[0, 1].ContextMenuStrip = this.ContextMenuStrip4;
也可以用CellContextMenuStripNeeded、RowContextMenuStripNeeded属性进行定义
[C#]
//CellitMenuStripNeeded事件处理程序
private void DataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex < 0)
{
//设置在列页眉上显示的控制程序
e.ContextMenuStrip = this.ContextMenuStrip1;
}
else if (e.ColumnIndex < 0)
{
//设置在行标题中显示的大纲视图
e.ContextMenuStrip = this.ContextMenuStrip2;
}
else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
{
//更改单元格是整数类型时要显示的大纲
e.ContextMenuStrip = this.ContextMenuStrip3;
}
}
20. 指定滚动框位置
[C#]
//滚动到开头的行
DataGridView1.FirstDisplayedScrollingRowIndex = 0;
//滚动到第一列
DataGridView1.FirstDisplayedScrollingColumnIndex = 0;
21. 手动追加列
[C#]
//不要自动制作列
DataGridView1.AutoGenerateColumns = false;
//设置数据源
DataGridView1.DataSource = BindingSource1;
//制作DataGridViewTecxColumn列
DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();
//绑定数据源中的列1
textColumn.DataPropertyName = "Column1";
//设定名字和页眉
textColumn.Name = "Column1";
textColumn.HeaderText = "Column1";
//添加列
DataGridView1.Columns.Add(textColumn);
22. 全体分界线样式设置
[C#]
//将DataGridView的边界线设置为3D
DataGridView1.BorderStyle = BorderStyle.Fixed3D;
单元格上下左右分界线样式设置
[C#]
//把单元格的上和左边分成两条线的边界线,
//向下和向右对齐一条重线的凹边界线
DataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble;
DataGridView1.AdvancedCellBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.Inset;
DataGridView1.AdvancedCellBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Inset;
DataGridView1.AdvancedCellBorderStyle.Left = DataGridViewAdvancedCellBorderStyle.InsetDouble;
23. 根据单元格属性更改显示内容
如下例,当该列是字符串时,自动转换文字大小写
[C#]
//Carelmatting事件韩剧
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;
}
}
24. 新追加行的行高样式设置的
行高设置
[C#]
//设置行模板的高度
DataGridView1.RowTemplate.Height = 50;
//设定行的最低高度
DataGridView1.RowTemplate.MinimumHeight = 50;
样式设置
[C#]
//将行模板的单元格样式为黄色
DataGridView1.DefaultCellStyle.BackColor = Color.Yellow;
25. 新追加行单元格默认值设置
[C#]
//DefaultValuesNeeded事件处理程序
private void DataGridView1_DefaultValuesNeeded(object sender,
DataGridViewRowEventArgs e)
{
//指定单元格的既定值
e.Row.Cells["Column1"].Value = 0;
e.Row.Cells["Column2"].Value = "-";
}
26. 单元格数据错误标签表示
[C#]
//(0,0)的单元格显示错误图标
DataGridView1[0, 0].ErrorText = "请确认单元格的值";
//索引在三行中显示错误图标
DataGridView1.Rows[3].ErrorText = "不能输入负值。";
在大量单元格需要错误提示时,也可以用CellErrorTextNeeded、RowErrorTextNeeded事件
[C#]
//CareErrorTectectentNER事件韩剧
private void DataGridView1_CellErrorTextNeeded(object sender,
DataGridViewCellErrorTextNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//如果单元格的值是负整数,则显示错误图标
object cellVal = dgv[e.ColumnIndex, e.RowIndex].Value;
if (cellVal is int && ((int)cellVal) < 0)
{
e.ErrorText = "不能输入负整数。";
}
}
//RoErrorTectectentNER事件韩剧
private void DataGridView1_RowErrorTextNeeded(object sender,
DataGridViewRowErrorTextNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv["Column1", e.RowIndex].Value == DBNull.Value &&
dgv["Column2", e.RowIndex].Value == DBNull.Value)
{
e.ErrorText =
"请至少在Column1和Column2中输入值。";
}
}
27. 单元格内输入值正确性判断
[C#]
//CellValidating事件处理程序
private void DataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.Columns[e.ColumnIndex].Name == "Column1" &&
e.FormattedValue.ToString() == "")
{
//设置错误文本
dgv.Rows[e.RowIndex].ErrorText = "没有输入值";
//要取消输入的值并将其还原为原始值,请执行以下操作:
dgv.CancelEdit();
//取消
e.Cancel = true;
}
}
//CareValidater事件汉剧
private void DataGridView1_CellValidated(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//删除错误文本
dgv.Rows[e.RowIndex].ErrorText = null;
}
28. 单元格输入错误值事件的捕获
[C#]
//DataError事件短剧
private void DataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
if (e.Exception != null)
{
MessageBox.Show(this,
string.Format("({0}, {1}) 的单元格中发生错误。nn说明: {2}",
e.ColumnIndex, e.RowIndex, e.Exception.Message),
"发生错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
输入错误值时返回原先数据
[C#]
//DataError事件短剧
private void DataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
e.Cancel = false;
}
29. 行排序(点击列表头自动排序的设置)
[C#]
//阻止排序
foreach (DataGridViewColumn c in DataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.NotSortable;
30. 自动行排序(新追加值也会自动排序)
[C#]
//格式的短剧
private void Form1_Load(object sender, EventArgs e)
{
//自动排列
foreach (DataGridViewColumn c in DataGridView1.Columns)
c.SortMode = DataGridViewColumnSortMode.Automatic;
}
//Button 1的Click事件韩剧
private void Button1_Click(object sender, EventArgs e)
{
if (DataGridView1.CurrentCell == null)
return;
//确定要重新排序的列
DataGridViewColumn sortColumn = DataGridView1.CurrentCell.OwningColumn;
//决定重新排列的方向(升序或降序)
ListSortDirection sortDirection = ListSortDirection.Ascending;
if (DataGridView1.SortedColumn != null &&
DataGridView1.SortedColumn.Equals(sortColumn))
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Ascending ?
ListSortDirection.Descending : ListSortDirection.Ascending;
}
//排序
DataGridView1.Sort(sortColumn, sortDirection);
}
31. 自动行排序禁止情况下的排序
[C#]
//格式的短剧
private void Form1_Load(object sender, EventArgs e)
{
//添加事件处理程序
DataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(
DataGridView1_RowsAdded);
DataGridView1.CellValueChanged += new DataGridViewCellEventHandler(
DataGridView1_CellValueChanged);
DataGridView1.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(
DataGridView1_ColumnHeaderMouseClick);
}
//ColumnHeaderMoug Click事件韩剧
private void DataGridView1_ColumnHeaderMouseClick(object sender,
DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn clickedColumn = DataGridView1.Columns[e.ColumnIndex];
if (clickedColumn.SortMode != DataGridViewColumnSortMode.Automatic)
this.SortRows(clickedColumn, true);
}
//RATsAW事件汉剧
private void DataGridView1_RowsAdded(object sender,
DataGridViewRowsAddedEventArgs e)
{
this.SortRows(DataGridView1.SortedColumn, false);
}
//CellValueChangedイベントハンドラ
private void DataGridView1_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
if (DataGridView1.SortedColumn != null &&
e.ColumnIndex == DataGridView1.SortedColumn.Index)
this.SortRows(DataGridView1.SortedColumn, false);
}
/// <summary>
/// 以指定的列为基准进行排序
/// </summary>
/// <param name="sortColumn">要参考的列</param>
/// <param name="orderToggle">把重新排列的方向改为角度</param>
private void SortRows(DataGridViewColumn sortColumn, bool orderToggle)
{
if (sortColumn == null)
return;
//清除以前的排序图示符
if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic &&
DataGridView1.SortedColumn != null &&
!DataGridView1.SortedColumn.Equals(sortColumn))
{
DataGridView1.SortedColumn.HeaderCell.SortGlyphDirection =
SortOrder.None;
}
//排序方向(升序或降序)
ListSortDirection sortDirection;
if (orderToggle)
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Descending ?
ListSortDirection.Ascending : ListSortDirection.Descending;
}
else
{
sortDirection =
DataGridView1.SortOrder == SortOrder.Descending ?
ListSortDirection.Descending : ListSortDirection.Ascending;
}
SortOrder sortOrder =
sortDirection == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
//排序排序排序
DataGridView1.Sort(sortColumn, sortDirection);
if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic)
{
//变更排列网格
sortColumn.HeaderCell.SortGlyphDirection = sortOrder;
}
}
32. 指定列指定排序
[C#]
//获得DataGridView 1的DataTable
DataTable dt = (DataTable)DataGridView1.DataSource;
//取得DataView
DataView dv = dt.DefaultView;
//在Column1和Column2中按升序排列
dv.Sort = "Column1, Column2 ASC";
//显示在两列的页眉上替换的网格
DataGridView1.Columns["Column1"].HeaderCell.SortGlyphDirection =
SortOrder.Ascending;
DataGridView1.Columns["Column2"].HeaderCell.SortGlyphDirection =
SortOrder.Ascending;
33. 单元格样式设置
指定行列的样式设定
[C#]
//为0的列的单元格的背景颜色为水色
DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Aqua;
//为0的行的单元格的背景色为薄灰色
DataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightGray;
奇数行样式设定
[C#]
//将奇数行的单元格的背景色变成黄绿颜色
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow;
行,列表头部的样式设定
[C#]
//将列页眉的背景颜色为眼角
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Ivory;
//将行页眉的背景颜色作为阴影
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Lime;
样式的优先顺序
一般单元格的样式优先顺位
- DataGridViewCell.Style
- DataGridViewRow.DefaultCellStyle
- DataGridView.AlternatingRowsDefaultCellStyle
- DataGridView.RowsDefaultCellStyle
- DataGridViewColumn.DefaultCellStyle
- DataGridView.DefaultCellStyle
表头部的样式优先顺位
- DataGridViewCell.Style
- DataGridView.RowHeadersDefaultCellStyle
- DataGridView.ColumnHeadersDefaultCellStyle
- DataGridView.DefaultCellStyle
下例说明
[C#]
//使第一列变成淡蓝色
DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Aqua;
//把所有列的背景颜色变成黄色
DataGridView1.RowsDefaultCellStyle.BackColor = Color.Yellow;
//使奇数行变成黄绿色
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.GreenYellow;
//把第三行画成粉红色
DataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Pink;
//获取自身的单元格样式和继承的单元格样式的背景色
//第一列的单元格样式
//表示“Acoa”和“[ Acoa ]”
Console.WriteLine(DataGridView1.Columns[0].DefaultCellStyle.BackColor);
Console.WriteLine(DataGridView1.Columns[0].InheritedStyle.BackColor);
//第一行的单元格样式
//表示“Emp晚餐”和“[ Yellow ]”
Console.WriteLine(DataGridView1.Rows[0].DefaultCellStyle.BackColor);
Console.WriteLine(DataGridView1.Rows[0].InheritedStyle.BackColor);
//第二行的单元格样式
//被显示为“空白空间”和“GreenGreen黄蜂”
Console.WriteLine(DataGridView1.Rows[1].DefaultCellStyle.BackColor);
Console.WriteLine(DataGridView1.Rows[1].InheritedStyle.BackColor);
//第三行的单元格样式
//被显示为“CameraPinketal”和“BSPinketal”。
Console.WriteLine(DataGridView1.Rows[2].DefaultCellStyle.BackColor);
Console.WriteLine(DataGridView1.Rows[2].InheritedStyle.BackColor);
//(0,3)的单元格样式
//被显示为“空白空间”和“BSPink服务器之间”。
Console.WriteLine(DataGridView1[0, 2].Style.BackColor);
Console.WriteLine(DataGridView1[0, 2].InheritedStyle.BackColor);
复数行列的样式设定
[C#]
//改变奇数列的背景颜色
//有效的方法
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.BackColor = Color.Yellow;
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
if (i % 2 == 0)
DataGridView1.Columns[i].DefaultCellStyle = cellStyle;
}
//非效率的方法
for (int i = 0; i < DataGridView1.Columns.Count; i++)
{
if (i % 2 == 0)
DataGridView1.Columns[i].DefaultCellStyle.BackColor = Color.Yellow;
}
34. 文字表示位置的设定
单元格的设定
[C#]
//“Column1”列的单元格的文本的配置和上下左右都在中央
DataGridView1.Columns["Column1"].DefaultCellStyle.Alignment =
DataGridViewContentAlignment.MiddleCenter;
表头的设定
[C#]
//“Column1”列的页眉的文本的配置和上下左右都在中央
DataGridView1.Columns["Column1"].HeaderCell.Style.Alignment =
DataGridViewContentAlignment.MiddleCenter;
35. 单元格内文字列换行
[C#]
//“Column1”列的单元格文本显示
DataGridView1.Columns["Column1"].DefaultCellStyle.WrapMode =
DataGridViewTriState.True;
//页眉也返回显示,如下
DataGridView1.Columns["Column1"].HeaderCell.Style.WrapMode =
DataGridViewTriState.True;
36. 单元格DBNull值表示的设定
[C#]
DataGridView1.DefaultCellStyle.NullValue = "(未指定)";
单元格内NullValue属性设定的值输入,表示单元格内为Null值
[C#]
DataGridView1.DefaultCellStyle.NullValue = "-";
DataGridView1.DefaultCellStyle.DataSourceNullValue = "X";
37. 单元格样式格式化
[C#]
//列的单元格中的文本格式指定为地区货币
DataGridView1.Columns[0].DefaultCellStyle.Format = "c";
DataGridView1.Columns[1].DefaultCellStyle.Format = "c";
//改变第二列的纹理
DataGridView1.Columns[1].DefaultCellStyle.FormatProvider =
new System.Globalization.CultureInfo("en-US");
38. 指定单元格颜色设定
光标下的单元格颜色自动变换
[C#]
//DataGridView1的CellMouseEnter事件处理程序
private void DataGridView1_CellMouseEnter(object sender,
DataGridViewCellEventArgs e)
{
//页眉以外的单元格
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//改变单元格样式
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
}
}
//DataGridView 1的CareMouy Lita活动汉剧
private void DataGridView1_CellMouseLeave(object sender,
DataGridViewCellEventArgs e)
{
//页眉以外的单元格
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//恢复单元格样式
//删除单元格样式时,可以设置null
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Empty;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Empty;
}
}
表头部单元格颜色设定
[C#]
//将列页眉的背景颜色为黄色
DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow;
//将行页眉的背景颜色变成黄绿颜色
DataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.YellowGreen;
//将左上角的标题单元格的背景色设为蓝色
DataGridView1.TopLeftHeaderCell.Style.BackColor = Color.Blue;
39. 单元格文字字体设置
光标下单元格字体设置为粗体
[C#]
//默认单元格样式
private DataGridViewCellStyle defaultCellStyle;
//鼠标指针下面的单元格样式
private DataGridViewCellStyle mouseCellStyle;
//格式的短剧
private void Form1_Load(object sender, EventArgs e)
{
//设置默认的单元格样式
this.defaultCellStyle = new DataGridViewCellStyle();
//设置当前单元格的单元格样式
this.mouseCellStyle = new DataGridViewCellStyle();
this.mouseCellStyle.Font = new Font(DataGridView1.Font,
DataGridView1.Font.Style | FontStyle.Bold);
}
//DataGridView 1的Caretal事件韩剧
private void DataGridView1_CellEnter(object sender,
DataGridViewCellEventArgs e)
{
//页眉以外的单元格
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//改变单元格样式
dgv[e.ColumnIndex, e.RowIndex].Style = this.mouseCellStyle;
}
}
//DataGridView 1的Celealae活动韩剧
private void DataGridView1_CellLeave(object sender,
DataGridViewCellEventArgs e)
{
//页眉以外的单元格
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
//恢复单元格样式
//删除单元格样式时,可以设置null
dgv[e.ColumnIndex, e.RowIndex].Style = this.defaultCellStyle;
}
}
40. 根据单元格值设定单元格样式
单元格负数情况下显示黄色,0的情况下显示红色
[C#]
// Celermatting事件韩剧
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//确认单元格的列
if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is int)
{
int val = (int)e.Value;
//根据单元格的值,改变背景颜色る
if (val < 0)
{
e.CellStyle.BackColor = Color.Yellow;
}
else if (val == 0)
{
e.CellStyle.BackColor = Color.Red;
}
}
}
41. 设置单元格背景颜色
[C#]
//CarePainting事件韩剧
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//在页眉以外的单元格中,绘制背景时
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
(e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//检查选择,决定颜色
//bColor 1开始颜色,bColor 2结束颜色
Color bColor1, bColor2;
if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground &&
(e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
bColor1 = e.CellStyle.SelectionBackColor;
bColor2 = Color.Black;
}
else
{
bColor1 = e.CellStyle.BackColor;
bColor2 = Color.LemonChiffon;
}
//制作渐变刷
using (System.Drawing.Drawing2D.LinearGradientBrush b =
new System.Drawing.Drawing2D.LinearGradientBrush(
e.CellBounds, bColor1, bColor2,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
//把单元格涂碎
e.Graphics.FillRectangle(b, e.CellBounds);
}
//显示背景以外
DataGridViewPaintParts paintParts =
e.PaintParts & ~DataGridViewPaintParts.Background;
//绘制单元格
e.Paint(e.ClipBounds, paintParts);
//通知绘制完成
e.Handled = true;
}
}
单元格背景显示图像
[C#]
//显示在单元格背景下的图像
private Bitmap cellBackImage = new Bitmap("C:\\back.gif");
//CarePainting事件韩剧
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//在页眉以外的单元格中,绘制背景时
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
(e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//只绘制背景
DataGridViewPaintParts backParts = e.PaintParts &
(DataGridViewPaintParts.Background |
DataGridViewPaintParts.SelectionBackground);
e.Paint(e.ClipBounds, backParts);
//在单元格中心绘制图像
int x = e.CellBounds.X +
(e.CellBounds.Width - cellBackImage.Width) / 2;
int y = e.CellBounds.Y +
(e.CellBounds.Height - cellBackImage.Height) / 2;
e.Graphics.DrawImage(cellBackImage, x, y);
//显示背景以外
DataGridViewPaintParts paintParts =
e.PaintParts & ~backParts;
//绘制单元格
e.Paint(e.ClipBounds, paintParts);
//通知绘制完成
e.Handled = true;
}
}
42. 行样式描画
利用RowPostPaint事件描画
[C#]
//RowPostPaint事件处理程序
private void DataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//确定线条的颜色
Pen linePen;
switch (e.RowIndex % 3)
{
case 0:
linePen = Pens.Blue;
break;
case 1:
linePen = Pens.Green;
break;
default:
linePen = Pens.Red;
break;
}
//计算划线的位置
int startX = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
int startY = e.RowBounds.Top + e.RowBounds.Height - 1;
int endX = startX + dgv.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
dgv.HorizontalScrollingOffset;
//划线
e.Graphics.DrawLine(linePen,
startX, startY, endX, startY);
}
利用RowPrePaint事件描画
[C#]
//RowPrePaint事件处理程序private void DataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
//绘制背景
if ((e.PaintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
//检查选择,决定颜色
//bColor 1开始颜色,bColor 2结束颜色
Color bColor1, bColor2;
if ((e.PaintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground &&
(e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
bColor1 = e.InheritedRowStyle.SelectionBackColor;
bColor2 = Color.Black;
}
else
{
bColor1 = e.InheritedRowStyle.BackColor;
bColor2 = Color.YellowGreen;
}
//计算渐变的范围
//只绘制不包含标题的单元格区域
DataGridView dgv = (DataGridView)sender;
int rectLeft2 = dgv.RowHeadersVisible ? dgv.RowHeadersWidth : 0;
int rectLeft = rectLeft2 - dgv.HorizontalScrollingOffset;
int rectWidth = dgv.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible);
Rectangle rect = new Rectangle(rectLeft, e.RowBounds.Top,
rectWidth, e.RowBounds.Height - 1);
//制作渐变刷
using (System.Drawing.Drawing2D.LinearGradientBrush b =
new System.Drawing.Drawing2D.LinearGradientBrush(
rect, bColor1, bColor2,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal))
{
//计算要绘制的范围
rect.X = rectLeft2;
rect.Width -= dgv.HorizontalScrollingOffset;
//把单元格涂碎
e.Graphics.FillRectangle(b, rect);
}
//绘制页眉
e.PaintHeader(true);
//不绘制背景
e.PaintParts &= ~DataGridViewPaintParts.Background;
}
}
//ColumnWidthChanged事件处理程序
private void DataGridView1_ColumnWidthChanged(object sender,
DataGridViewColumnEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
dgv.Invalidate();
}
43. 显示行号
[C#]
//CarePainting事件韩剧
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//检查列标题
if (e.ColumnIndex < 0 && e.RowIndex >= 0)
{
//绘制单元格
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
//确定绘制行号的范围
//e . AXestiBordersteryle和e . Cirstyle . Padding是无视的
Rectangle indexRect = e.CellBounds;
indexRect.Inflate(-2, -2);
//绘制行号
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.CellStyle.Font,
indexRect,
e.CellStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
//通知绘制完成
e.Handled = true;
}
}
利用RowPostPaint事件描画
[C#]
//RowPostPaint事件处理程序
private void DataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.RowHeadersVisible)
{
//确定绘制行号的范围
Rectangle rect = new Rectangle(
e.RowBounds.Left, e.RowBounds.Top,
dgv.RowHeadersWidth, e.RowBounds.Height);
rect.Inflate(-2, -2);
//绘制行号
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.InheritedRowStyle.Font,
rect,
e.InheritedRowStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
}
}
44. 焦点所在单元格焦点框不显示的设定
[C#]
//CarePainting事件韩剧
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
//非标题时
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
//显示除了聚焦框以外
DataGridViewPaintParts paintParts =
e.PaintParts & ~DataGridViewPaintParts.Focus;
//绘制单元格
e.Paint(e.ClipBounds, paintParts);
//通知绘制完成
e.Handled = true;
}
}
利用RowPrePaint事件实现
[C#]
//RowPrePaint事件处理程序
private void DataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
//不绘制焦点框架
e.PaintParts &= ~DataGridViewPaintParts.Focus;
}
45. 列中显示选择框CheckBox
[C#]
//添加CheckBx列
DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
DataGridView1.Columns.Add(column);
中间状态在内的三种状态表示
[C#]
//显示3种检查状态
DataGridViewCheckBoxColumn column =
(DataGridViewCheckBoxColumn)DataGridView1.Columns[0];
column.ThreeState = true;
46. 中显示下拉框ComboBox
[C#]
//制作DataGridViewampColumn
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
//指定在ComboBox的列表中显示的项目
column.Items.Add("日曜日");
column.Items.Add("月曜日");
column.Items.Add("火曜日");
column.Items.Add("水曜日");
column.Items.Add("木曜日");
column.Items.Add("金曜日");
column.Items.Add("土曜日");
//显示“Week”列中绑定的数据
column.DataPropertyName = "Week";
//显示ComboBox列而不是“Week”列
DataGridView1.Columns.Insert(DataGridView1.Columns["Week"].Index, column);
DataGridView1.Columns.Remove("Week");
column.Name = "Week";
通过列Data绑定设置ComboBox
[C#]
//创建一个用于在ComboBox中显示的列表
DataTable weekTable = new DataTable("WeekTable");
weekTable.Columns.Add("Display", typeof(string));
weekTable.Columns.Add("Value", typeof(int));
weekTable.Rows.Add("日曜日", 0);
weekTable.Rows.Add("月曜日", 1);
weekTable.Rows.Add("火曜日", 2);
weekTable.Rows.Add("水曜日", 3);
weekTable.Rows.Add("木曜日", 4);
weekTable.Rows.Add("金曜日", 5);
weekTable.Rows.Add("土曜日", 6);
//制作DataGridViewampColumn
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
//显示“Week”列中绑定的数据
column.DataPropertyName = "Week";
//设定DataGridViewampColumn的Datasouru
column.DataSource = weekTable;
//实际值为“值”列,显示的文本为“显示”列
column.ValueMember = "Value";
column.DisplayMember = "Display";
//添加到DataGridView1
DataGridView1.Columns.Add(column);
默认状态下,所有下拉框都显示;DisplayStyleForCurrentCellOnly=True的状态下,当前的单元格显示下拉框,其余不显示;还有一种就是光标移动时强调显示。如下图左中右三列。
47. 单击打开下拉框
通常情况下要打开下拉框需要点击目标单元格三次,第一次选中单元格,第二次进入编辑状态,第三次才能打开下拉框
[C#]
//Caretal事件韩剧
private void DataGridView1_CellEnter(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.Columns[e.ColumnIndex].Name == "ComboBox" &&
dgv.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
{
SendKeys.Send("{F4}");
}
}
48. 中显示按钮
[C#]
// DataGridViewButtonColumn的制作
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
//设置列的名称
column.Name = "Button";
/ /在所有的按钮上显示“详细阅览”
column.UseColumnTextForButtonValue = true;
column.Text = "详细阅览";
添加到//DataGridView
DataGridView1.Columns.Add(column);
按钮按下事件取得
[C#]
//Celertent Click事件韩剧
private void DataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//“Button”列的话,按钮被点击了
if (dgv.Columns[e.ColumnIndex].Name == "Button")
{
MessageBox.Show(e.RowIndex.ToString() +
"行的按钮被点击了");
}
}
49. 中显示链接
[C#]
//创建DataGridViewLinkColumn
DataGridViewLinkColumn column = new DataGridViewLinkColumn();
//设置列的名称
column.Name = "Link";
//在所有链接上显示“详细阅览”
column.UseColumnTextForLinkValue = true;
column.Text = "详细阅览";
//鼠标指针在链接上的时候只需下线
column.LinkBehavior = LinkBehavior.HoverUnderline;
//自动访问
//默认
column.TrackVisitedState = true;
//添加到DataGridView
DataGridView1.Columns.Add(column);
链接按下事件取得
[C#]
//Celertent Click事件韩剧
private void DataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//“Link”列的话,按钮被点击了
if (dgv.Columns[e.ColumnIndex].Name == "Link")
{
MessageBox.Show(e.RowIndex.ToString() +
"单击行中的链接。");
//访问
DataGridViewLinkCell cell =
(DataGridViewLinkCell)dgv[e.ColumnIndex, e.RowIndex];
cell.LinkVisited = true;
}
}
50. 中显示图像
[C#]
//创建DataGridViewImageColumn
DataGridViewImageColumn column = new DataGridViewImageColumn();
//设置列的名称
column.Name = "Image";
//不是Icon型,而是显示Image型的数据
//默认False变更的,所以没有必要
column.ValuesAreIcons = false;
//设置显示在没有设定值的单元格中的图像
column.Image = new Bitmap("C:\\null.gif");
//保持垂直比例,放大显示图像
column.ImageLayout = DataGridViewImageCellLayout.Zoom;
//图像说明
//将单元格复制到剪切板时使用
column.Description = "图像";
//添加到DataGridView
DataGridView1.Columns.Add(column);
//更改“图像”列顶部的单元格图像
DataGridView1["Image", 0].Value = new Bitmap("C:\\top.gif");
图片属性单元格未设值时红差不显示的设定
[C#]
//获取图像列
DataGridViewImageColumn imageColumn =
(DataGridViewImageColumn)DataGridView1.Columns["Image"];
//将单元格样式的NullValue设置为null
imageColumn.DefaultCellStyle.NullValue = null;
51. 编辑中单元格控件取得
[C#]
//Editing联合活动韩剧
private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
//检查显示的控件是否为DataGridViewTextBoxEditingControl
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridView dgv = (DataGridView)sender;
//获得编辑所显示的控制
DataGridViewTextBoxEditingControl tb =
(DataGridViewTextBoxEditingControl)e.Control;
/也可以如下
//TextBox tb = (TextBox)e.Control;
//通过列更改IME的模式
if (dgv.CurrentCell.OwningColumn.Name == "Column1")
tb.ImeMode = ImeMode.Disable;
else
tb.ImeMode = dgv.ImeMode;
}
}
其他控件以此类推,比如DataGridViewCheckBoxColumn或者DataGridViewButtonColumn等等。
52. 输入自动完成
[C#]
AutoCompleteStringCollection autoCompleteSource =
new AutoCompleteStringCollection();
//Editing联合活动韩剧
private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.Control is TextBox)
{
//获得编辑所显示的文本框
TextBox tb = (TextBox)e.Control;
//相应地调查
if (dgv.CurrentCell.OwningColumn.Name == "Column1")
{
//启用自动压缩机
tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
tb.AutoCompleteCustomSource = this.autoCompleteSource;
}
else
{
//禁用自动完成
tb.AutoCompleteMode = AutoCompleteMode.None;
}
}
}
//DataSourceChanged事件韩剧
private void DataGridView1_DataSourceChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//初始化自动压缩机列表
this.autoCompleteSource.Clear();
//将DataGridView中的数据添加到列表
foreach (DataGridViewRow r in dgv.Rows)
{
//获取单元格值
string val = r.Cells["Column1"].Value as string;
if (!string.IsNullOrEmpty(val) &&
!this.autoCompleteSource.Contains(val))
{
//添加到自动压缩机列表
autoCompleteSource.Add(val);
}
}
}
//CellValueChanged事件处理程序
private void DataGridView1_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//相应地调查
if (dgv.Columns[e.ColumnIndex].Name == "Column1")
{
//获取单元格值
string val = dgv[e.ColumnIndex, e.RowIndex].Value as string;
if (!string.IsNullOrEmpty(val) &&
!this.autoCompleteSource.Contains(val))
{
//添加到自动压缩机列表
autoCompleteSource.Add(val);
}
}
}
53. 单元格编辑时键盘KEY事件取得
[C#]
//Editing联合活动韩剧
private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
//检查显示的控件是否为DataGridViewTextBoxEditingControl
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridView dgv = (DataGridView)sender;
//获得编辑所显示的控制
DataGridViewTextBoxEditingControl tb =
(DataGridViewTextBoxEditingControl)e.Control;
//删除事件
tb.KeyPress -=
new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
//相应地调查
if (dgv.CurrentCell.OwningColumn.Name == "Column1")
{
//添加KeyPress事件处理程序
tb.KeyPress +=
new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}
}
}
//在DataGridView中显示的文本框的KeyPres事件
private void dataGridViewTextBox_KeyPress(object sender,
KeyPressEventArgs e)
{
//只需输入数字
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
}
}
54. 下拉框(ComboBox)单元格编辑时事件取得
[C#]
private DataGridViewComboBoxEditingControl dataGridViewComboBox = null;
//Editing联合活动韩剧
private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
//显示的控制是Dat a G r i d V V V V Viewamiting管理
if (e.Control is DataGridViewComboBoxEditingControl)
{
DataGridView dgv = (DataGridView)sender;
//相应地调查
if (dgv.CurrentCell.OwningColumn.Name == "ComboBox")
{
//获得编辑所显示的控制
this.dataGridViewComboBox =
(DataGridViewComboBoxEditingControl)e.Control;
//添加“SelectadIndeChanged事件”事件
this.dataGridViewComboBox.SelectedIndexChanged +=
new EventHandler(dataGridViewComboBox_SelectedIndexChanged);
}
}
}
//CellEndEdit事件处理程序
private void DataGridView1_CellEndEdit(object sender,
DataGridViewCellEventArgs e)
{
//删除“SelectadIndeChanged事件”事件
if (this.dataGridViewComboBox != null)
{
this.dataGridViewComboBox.SelectedIndexChanged -=
new EventHandler(dataGridViewComboBox_SelectedIndexChanged);
this.dataGridViewComboBox = null;
}
}
//在DataGridView中显示的转换器的
//SelectadIndeChanged事件韩剧
private void dataGridViewComboBox_SelectedIndexChanged(object sender,
EventArgs e)
{
//显示选择的项目
DataGridViewComboBoxEditingControl cb =
(DataGridViewComboBoxEditingControl)sender;
Console.WriteLine(cb.SelectedItem);
}
55. 下拉框(ComboBox)单元格允许文字输入设定
[C#]
//Editing联合活动韩剧
private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewComboBoxEditingControl)
{
//相应地调查
DataGridView dgv = (DataGridView)sender;
if (dgv.CurrentCell.OwningColumn.Name == "ComboBox")
{
//获得编辑所显示的控制
DataGridViewComboBoxEditingControl cb =
(DataGridViewComboBoxEditingControl)e.Control;
cb.DropDownStyle = ComboBoxStyle.DropDown;
}
}
}
//CellValidating事件处理程序
private void DataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//相应地调查
if (dgv.Columns[e.ColumnIndex].Name == "ComboBox" &&
dgv.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
{
DataGridViewComboBoxColumn cbc =
(DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex];
//添加到转换器的项目
if (!cbc.Items.Contains(e.FormattedValue))
{
cbc.Items.Add(e.FormattedValue);
}
}
}
56. 根据值不同在另一列中显示相应图片
[C#]
using System;
using System.ComponentModel;
using System.Windows.Forms;
/// <summary>
/// 根据单元格的值,显示适当的图标
/// </summary>
public class DataGridViewErrorIconColumn : DataGridViewImageColumn
{
public DataGridViewErrorIconColumn()
{
this.CellTemplate = new DataGridViewErrorIconCell();
this.ValueType = this.CellTemplate.ValueType;
}
}
/// <summary>
///根据单元格的值,显示适当的图标
/// </summary>
public class DataGridViewErrorIconCell : DataGridViewImageCell
{
public DataGridViewErrorIconCell()
{
this.ValueType = typeof(int);
}
protected override object GetFormattedValue(
object value, int rowIndex,
ref DataGridViewCellStyle cellStyle,
TypeConverter valueTypeConverter,
TypeConverter formattedValueTypeConverter,
DataGridViewDataErrorContexts context)
{
//值为0时为信息,1时为警告,2时显示错误图标
switch ((int)value)
{
case 1:
return SystemIcons.Information;
case 2:
return SystemIcons.Warning;
case 3:
return SystemIcons.Error;
default:
return null;
}
}
public override object DefaultNewRowValue
{
get
{
return 0;
}
}
}
用法如下
[C#]
//制作DataGridViewErrorICOColumn
DataGridViewErrorIconColumn iconColumn =
new DataGridViewErrorIconColumn();
//拉拢Column一列(整数型)
iconColumn.DataPropertyName = "Column1";
//添加到DataGridView
DataGridView1.Columns.Add(iconColumn);
57. 中显示进度条(ProgressBar)
[C#]
using System;
using System.Drawing;
using System.Windows.Forms;
/// <summary>
///DatagridViewchsBarCel对象列
/// </summary>
public class DataGridViewProgressBarColumn : DataGridViewTextBoxColumn
{
//转换器
public DataGridViewProgressBarColumn()
{
this.CellTemplate = new DataGridViewProgressBarCell();
}
//检索和设置CellTemplate。
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
//除了DataGridViewchsBarCel以外不做主机
if (!(value is DataGridViewProgressBarCell))
{
throw new InvalidCastException(
"DatagridViewchsBarCel对象" +
"请指定");
}
base.CellTemplate = value;
}
}
/// <summary>
/// 显示的最大值的最大数量
/// </summary>
public int Maximum
{
get
{
return ((DataGridViewProgressBarCell)this.CellTemplate).Maximum;
}
set
{
if (this.Maximum == value)
return;
//更改单元格模板的值
((DataGridViewProgressBarCell)this.CellTemplate).Maximum =
value;
//改变已添加到DataGridView的单元格的值
if (this.DataGridView == null)
return;
int rowCount = this.DataGridView.RowCount;
for (int i = 0; i < rowCount; i++)
{
DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);
((DataGridViewProgressBarCell)r.Cells[this.Index]).Maximum =
value;
}
}
}
/// <summary>
/// 最小值
/// </summary>
public int Mimimum
{
get
{
return ((DataGridViewProgressBarCell)this.CellTemplate).Mimimum;
}
set
{
if (this.Mimimum == value)
return;
//更改单元格模板的值
((DataGridViewProgressBarCell)this.CellTemplate).Mimimum =
value;
//改变已添加到DataGridView的单元格的值
if (this.DataGridView == null)
return;
int rowCount = this.DataGridView.RowCount;
for (int i = 0; i < rowCount; i++)
{
DataGridViewRow r = this.DataGridView.Rows.SharedRow(i);
((DataGridViewProgressBarCell)r.Cells[this.Index]).Mimimum =
value;
}
}
}
}
/// <summary>
///在DataGridView中显示一个示例
/// </summary>
public class DataGridViewProgressBarCell : DataGridViewTextBoxCell
{
//转换器
public DataGridViewProgressBarCell()
{
this.maximumValue = 100;
this.mimimumValue = 0;
}
private int maximumValue;
public int Maximum
{
get
{
return this.maximumValue;
}
set
{
this.maximumValue = value;
}
}
private int mimimumValue;
public int Mimimum
{
get
{
return this.mimimumValue;
}
set
{
this.mimimumValue = value;
}
}
//指定单元格值的数据类型
//这里是整数型
public override Type ValueType
{
get
{
return typeof(int);
}
}
//指定新记录行的单元格的既定值
public override object DefaultNewRowValue
{
get
{
return 0;
}
}
//因为添加了新属性,所以
// 需要超过Clo方法
public override object Clone()
{
DataGridViewProgressBarCell cell =
(DataGridViewProgressBarCell)base.Clone();
cell.Maximum = this.Maximum;
cell.Mimimum = this.Mimimum;
return cell;
}
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)
{
//决定值
int intValue = 0;
if (value is int)
intValue = (int)value;
if (intValue < this.mimimumValue)
intValue = this.mimimumValue;
if (intValue > this.maximumValue)
intValue = this.maximumValue;
//计算百分比
double rate = (double)(intValue - this.mimimumValue) /
(this.maximumValue - this.mimimumValue);
//绘制单元格的边界线
if ((paintParts & DataGridViewPaintParts.Border) ==
DataGridViewPaintParts.Border)
{
this.PaintBorder(graphics, clipBounds, cellBounds,
cellStyle, advancedBorderStyle);
}
//在边界线内侧取得范围
Rectangle borderRect = this.BorderWidths(advancedBorderStyle);
Rectangle paintRect = new Rectangle(
cellBounds.Left + borderRect.Left,
cellBounds.Top + borderRect.Top,
cellBounds.Width - borderRect.Right,
cellBounds.Height - borderRect.Bottom);
//决定背景颜色
//在未选择时更改颜色
bool isSelected =
(cellState & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected;
Color bkColor;
if (isSelected &&
(paintParts & DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground)
{
bkColor = cellStyle.SelectionBackColor;
}
else
{
bkColor = cellStyle.BackColor;
}
//绘制背景
if ((paintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
using (SolidBrush backBrush = new SolidBrush(bkColor))
{
graphics.FillRectangle(backBrush, paintRect);
}
}
//扣除Padding
paintRect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
paintRect.Width -= cellStyle.Padding.Horizontal;
paintRect.Height -= cellStyle.Padding.Vertical;
//绘制程序
if ((paintParts & DataGridViewPaintParts.ContentForeground) ==
DataGridViewPaintParts.ContentForeground)
{
if (ProgressBarRenderer.IsSupported)
{
//用visual风格绘制
//绘制序号
ProgressBarRenderer.DrawHorizontalBar(graphics, paintRect);
//在显示栏上绘制栏
Rectangle barBounds = new Rectangle(
paintRect.Left + 3, paintRect.Top + 3,
paintRect.Width - 4, paintRect.Height - 6);
barBounds.Width = (int)Math.Round(barBounds.Width * rate);
ProgressBarRenderer.DrawHorizontalChunks(graphics, barBounds);
}
else
{
//无法在视觉样式中绘制时
graphics.FillRectangle(Brushes.White, paintRect);
graphics.DrawRectangle(Pens.Black, paintRect);
Rectangle barBounds = new Rectangle(
paintRect.Left + 1, paintRect.Top + 1,
paintRect.Width - 1, paintRect.Height - 1);
barBounds.Width = (int)Math.Round(barBounds.Width * rate);
graphics.FillRectangle(Brushes.Blue, barBounds);
}
}
//显示焦点的框架
if (this.DataGridView.CurrentCellAddress.X == this.ColumnIndex &&
this.DataGridView.CurrentCellAddress.Y == this.RowIndex &&
(paintParts & DataGridViewPaintParts.Focus) ==
DataGridViewPaintParts.Focus &&
this.DataGridView.Focused)
{
//适当决定聚焦框的大小
Rectangle focusRect = paintRect;
focusRect.Inflate(-3, -3);
ControlPaint.DrawFocusRectangle(graphics, focusRect);
//指定背景色并绘制焦点框时
//ControlPaint.DrawFocusRectangle(
// graphics, focusRect, Color.Empty, bkColor);
}
//显示文本
if ((paintParts & DataGridViewPaintParts.ContentForeground) ==
DataGridViewPaintParts.ContentForeground)
{
//确定要显示的文本
string txt = string.Format("{0}%", Math.Round(rate * 100));
//string txt = formattedValue.ToString();
//原本,应该根据cellStyle决定TextFormatFlags。
TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter;
//确定颜色
Color fColor = cellStyle.ForeColor;
//if (isSelected)
// fColor = cellStyle.SelectionForeColor;
//else
// fColor = cellStyle.ForeColor;
//绘制文本
paintRect.Inflate(-2, -2);
TextRenderer.DrawText(graphics, txt, cellStyle.Font,
paintRect, fColor, flags);
}
//显示错误图标
if ((paintParts & DataGridViewPaintParts.ErrorIcon) ==
DataGridViewPaintParts.ErrorIcon &&
this.DataGridView.ShowCellErrors &&
!string.IsNullOrEmpty(errorText))
{
//取得显示错误图标的区域
Rectangle iconBounds = this.GetErrorIconBounds(
graphics, cellStyle, rowIndex);
iconBounds.Offset(cellBounds.X, cellBounds.Y);
//绘制错误图标
this.PaintErrorIcon(graphics, iconBounds, cellBounds, errorText);
}
}
}
用法如下
[C#]
//制作Data GridViewensBarColumn
DataGridViewProgressBarColumn pbColumn =
new DataGridViewProgressBarColumn();
//绑定数据源中的列1
pbColumn.DataPropertyName = "Column1";
//添加列
DataGridView1.Columns.Add(pbColumn);
58. 中添加MaskedTextBox
[C#]
using System;
using System.Windows.Forms;
/// <summary>
/// 表示Data GridViewMaskelxCel对象的列。
/// </summary>
public class DataGridViewMaskedTextBoxColumn :
DataGridViewColumn
{
//指定作为CareTempato的Data GridViewMaskadkelxCel对象
//调用基本类的转换器
public DataGridViewMaskedTextBoxColumn()
: base(new DataGridViewMaskedTextBoxCell())
{
}
private string maskValue = "";
/// <summary>
/// 适用于MaskadTetBx的Mask属性的值
/// </summary>
public string Mask
{
get
{
return this.maskValue;
}
set
{
this.maskValue = value;
}
}
//因为添加了新属性,所以
// 需要超过Clo方法
public override object Clone()
{
DataGridViewMaskedTextBoxColumn col =
(DataGridViewMaskedTextBoxColumn)base.Clone();
col.Mask = this.Mask;
return col;
}
//检索和设置CellTemplate。
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
//只能说一句话
// 阻止为CellTemplate设置
if (!(value is DataGridViewMaskedTextBoxCell))
{
throw new InvalidCastException(
"Dat a GridViewMaskadtemtvxCel对象" +
"请指定");
}
base.CellTemplate = value;
}
}
}
/// <summary>
///可以在MaskadTectBx中编辑的文本信息
/// 显示在DataGridView控件中。
/// </summary>
public class DataGridViewMaskedTextBoxCell :
DataGridViewTextBoxCell
{
//コンストラクタ
public DataGridViewMaskedTextBoxCell()
{
}
//初始化编辑控件
//编辑控制需要在另一个单元格和列中使用,因此需要初始化
public override void InitializeEditingControl(
int rowIndex, object initialFormattedValue,
DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex,
initialFormattedValue, dataGridViewCellStyle);
//获取编辑控制
DataGridViewMaskedTextBoxEditingControl maskedBox =
this.DataGridView.EditingControl as
DataGridViewMaskedTextBoxEditingControl;
if (maskedBox != null)
{
//设置Tect
maskedBox.Text =
this.Value != null ? this.Value.ToString() : "";
//反映自定义列属性
DataGridViewMaskedTextBoxColumn column =
this.OwningColumn as DataGridViewMaskedTextBoxColumn;
if (column != null)
{
maskedBox.Mask = column.Mask;
}
}
}
//指定编辑控制的类型
public override Type EditType
{
get
{
return typeof(DataGridViewMaskedTextBoxEditingControl);
}
}
//指定单元格值的数据类型
//在这里,作为Object
//和基本班一样,没有必要超重
public override Type ValueType
{
get
{
return typeof(object);
}
}
//指定新记录行的单元格的既定值
public override object DefaultNewRowValue
{
get
{
return base.DefaultNewRowValue;
}
}
}
/// <summary>
/// 用Data GridViewMaskadTectvxCel来担任主机
/// 表示MaskedTextBox控件。
/// </summary>
public class DataGridViewMaskedTextBoxEditingControl :
MaskedTextBox, IDataGridViewEditingControl
{
//显示了编辑控制的DataGridView
DataGridView dataGridView;
//显示编辑控制的行
int rowIndex;
//编辑控制的值和单元格的值是否不同
bool valueChanged;
//转换器
public DataGridViewMaskedTextBoxEditingControl()
{
this.TabStop = false;
}
#region IDataGridViewEditingControl 成员
//由编辑控制改变的单元格的值
public object GetEditingControlFormattedValue(
DataGridViewDataErrorContexts context)
{
return this.Text;
}
//由编辑控制改变的单元格的值
public object EditingControlFormattedValue
{
get
{
return this.GetEditingControlFormattedValue(
DataGridViewDataErrorContexts.Formatting);
}
set
{
this.Text = (string)value;
}
}
//将单元格样式应用于编辑控制
//将编辑控制的前景色,背景颜色,字体等组合成单元格样式
public void ApplyCellStyleToEditingControl(
DataGridViewCellStyle dataGridViewCellStyle)
{
this.Font = dataGridViewCellStyle.Font;
this.ForeColor = dataGridViewCellStyle.ForeColor;
this.BackColor = dataGridViewCellStyle.BackColor;
switch (dataGridViewCellStyle.Alignment)
{
case DataGridViewContentAlignment.BottomCenter:
case DataGridViewContentAlignment.MiddleCenter:
case DataGridViewContentAlignment.TopCenter:
this.TextAlign = HorizontalAlignment.Center;
break;
case DataGridViewContentAlignment.BottomRight:
case DataGridViewContentAlignment.MiddleRight:
case DataGridViewContentAlignment.TopRight:
this.TextAlign = HorizontalAlignment.Right;
break;
default:
this.TextAlign = HorizontalAlignment.Left;
break;
}
}
//有编辑单元格的DataGridView
public DataGridView EditingControlDataGridView
{
get
{
return this.dataGridView;
}
set
{
this.dataGridView = value;
}
}
//正在编辑的行的索引
public int EditingControlRowIndex
{
get
{
return this.rowIndex;
}
set
{
this.rowIndex = value;
}
}
//值是否改变
//编辑控制的值和单元格的值是否不同
public bool EditingControlValueChanged
{
get
{
return this.valueChanged;
}
set
{
this.valueChanged = value;
}
}
//指定的键由DataGridView处理,还是编辑控制?
//重回跟踪,编辑控制处理
//dataGridViewWantsInputKey为True时,DataGridView可以处理
public bool EditingControlWantsInputKey(
Keys keyData, bool dataGridViewWantsInputKey)
{
//Keys.REF.Right,Right,Home,End的时候,还将返回
//如果不这样做,用这些键把焦点转移到另一个单元格里
switch (keyData & Keys.KeyCode)
{
case Keys.Right:
case Keys.End:
case Keys.Left:
case Keys.Home:
return true;
default:
return false;
}
}
//鼠标光标指定在Editing Panel上时的光标
//EditingPanel是用于托管编辑控件的面板。
//编辑控件小于单元时,控件以外的部分变为面板
public Cursor EditingPanelCursor
{
get
{
return base.Cursor;
}
}
//以控制方式进行编辑
//将文本作为选择状态,或将插入指针作为结尾
public void PrepareEditingControlForEdit(bool selectAll)
{
if (selectAll)
{
//处于选择状态
this.SelectAll();
}
else
{
//把插入指针放在末尾
this.SelectionStart = this.TextLength;
}
}
//值更改时是否更改单元格的位置
//当值改变时,编辑控制的大小被改变时
public bool RepositionEditingControlOnValueChange
{
get
{
return false;
}
}
#endregion
//值已更改
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
//通知DataGridView值已更改
this.valueChanged = true;
this.dataGridView.NotifyCurrentCellDirty(true);
}
}
用法如下
[C#]
//制作Dat at ag idViewMaskadTectvxColumn
DataGridViewMaskedTextBoxColumn maskedColumn =
new DataGridViewMaskedTextBoxColumn();
//显示数据源的“Column1”
maskedColumn.DataPropertyName = "Column1";
//设定MaskadTetBx的Mask属性的值
maskedColumn.Mask = "000";
//在DataGridView中添加列
DataGridView1.Columns.Add(maskedColumn);
59. 中Enter键按下焦点移至旁边的单元格
[C#]
using System;
using System.Windows.Forms;
/// <summary>
///在按钮被按下时,与Tab键按下的相同动作
/// (将现在的单元格移动到旁边的单元格)DataGridView
/// </summary>
public class DataGridViewEx : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
//当按下EEB键时,Tab键被推了
if ((keyData & Keys.KeyCode) == Keys.Enter)
{
return this.ProcessTabKey(keyData);
}
return base.ProcessDialogKey(keyData);
}
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
//当按下EEB键时,Tab键被推了
if (e.KeyCode == Keys.Enter)
{
return this.ProcessTabKey(e.KeyCode);
}
return base.ProcessDataGridViewKey(e);
}
}
60. 行集合化(Group)
[C#]
//默认单元格样式
private DataGridViewCellStyle defaultCellStyle;
//分组的顶部行的单元格样式
private DataGridViewCellStyle groupCellStyle;
//格式的短剧
private void Form1_Load(object sender, EventArgs e)
{
//设置单元格样式
this.defaultCellStyle = new DataGridViewCellStyle();
this.groupCellStyle = new DataGridViewCellStyle();
this.groupCellStyle.ForeColor = Color.White;
this.groupCellStyle.BackColor = Color.DarkGreen;
this.groupCellStyle.SelectionBackColor = Color.DarkBlue;
}
//Carelmatting事件韩剧
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//单元格是第一列,不是页眉,也不是新的行时
if (e.ColumnIndex == 0 && e.RowIndex >= 0 &&
e.RowIndex != dgv.NewRowIndex)
{
if (e.RowIndex == 0 ||
!dgv[e.ColumnIndex, e.RowIndex - 1].Value.Equals(e.Value))
{
//第一行或与上单元格不同的值时,改变背景颜色
dgv.Rows[e.RowIndex].DefaultCellStyle = this.groupCellStyle;
}
else
{
dgv.Rows[e.RowIndex].DefaultCellStyle = this.defaultCellStyle;
e.Value = "";
e.FormattingApplied = true;
}
}
}