1.只显示自定义列
dataGridView1.AutoGenerateColumns = false;//必须在代码中设置
2.禁止调整行、列大小
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;//禁止手工调整标题行高度 dataGridView1.AllowUserToResizeRows = false; //禁止手工调整行大小 dataGridView1.AllowUserToResizeColumns = false; //禁止手工调整列大小
3.单元格内容格式化
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridView myDataGridView = (DataGridView)sender; if (myDataGridView.Columns["ID"].Index == e.ColumnIndex) { if(e.Value != null && !string.IsNullOrEmpty(e.Value.ToString())) e.Value = "BH" + string.Format("{0:D8}", int.Parse(e.Value.ToString())); } }
4.修改行文字颜色/行背景色
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("column_name")) { if (e.Value.ToString() == "失败") { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red; //行文字颜色 //dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; //行背景色 } } }
5.右键点击行时选中行,并弹出操作菜单
①. 添加一个快捷菜单contextMenuStrip1;
②. 给dataGridView1的CellMouseDown事件添加处理程序:
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (e.RowIndex >= 0) { //若行已是选中状态就不再进行设置 if (dataGridView1.Rows[e.RowIndex].Selected == false) { dataGridView1.ClearSelection(); dataGridView1.Rows[e.RowIndex].Selected = true; } //只选中一行时设置活动单元格 if (dataGridView1.SelectedRows.Count == 1) { dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; } //弹出操作菜单 contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } } }
效果图:
6.复制选中单元格的内容到剪贴板
//复制选中内容 Clipboard.SetDataObject(dataGridView1.GetClipboardContent()); //复制选中行某列内容 if (dataGridView1.SelectedRows.Count > 0) { Clipboard.SetText(dataGridView1.SelectedRows[0].Cells["Title"].Value.ToString()); }
7.自定义列宽
手动添加列,再在编辑列界面中逐个设置宽度。注意AutoSizeColumnsMode的值必须为DataGridViewAutoSizeColumnsMode.None,否则自定义宽度不能生效!
8.打造一个漂亮的DataGridView
//样式 dataGridView1.RowHeadersVisible = false; //不显示行标题列 //dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //列自动充满DataGridView dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon;//奇数行背景色 dataGridView1.BackgroundColor = Color.White;//控件背景色 dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示 dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//单元格内容居中显示 //行为 dataGridView1.AutoGenerateColumns = false;//不自动创建列 dataGridView1.AllowUserToAddRows = false;//不启用添加 dataGridView1.ReadOnly = true;//不启用编辑 dataGridView1.AllowUserToDeleteRows = false;//不启用删除 dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;//禁止手工调整标题行高度 dataGridView1.AllowUserToResizeRows = false; //禁止手工调整行大小 dataGridView1.AllowUserToResizeColumns = false; //禁止手工调整列大小 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//单击单元格选中整行 dataGridView1.MultiSelect = false;//禁用多选
9.显示图片
通常,我们将图片路径保存在数据库中,但在dataGridView1中要显示图片,可以进行如下操作:
①.添加一个DataGridViewTextBoxColumn类型的列,Name=Path,DataPropertyName=Pic,Visible=False;
②.添加一个DataGridViewImageColumn类型的列,Name=Pic;
③.dataGridView1控件DataBindingComplete事件处理程序如下:
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { Image image1 = null; Image image2 = null; string path = string.Empty; for (int i = 0; i < dataGridView1.Rows.Count; i++) { path = @"F:\" + dataGridView1.Rows[i].Cells["Path"].Value; if (File.Exists(path)) { image1 = Image.FromFile(path); image2 = new Bitmap(image1, 120, 120);//重设大小 dataGridView1.Rows[i].Cells["Pic"].Value = image2; //((DataGridViewImageCell)dataGridView1.Rows[i].Cells["Pic"]).Value = image2; } } }
10.当网格未填充满控件时,画线来填充空白区域
/// <summary> /// 绘制网格填充空白区域 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { DataGridView myDataGridView = (DataGridView)sender; if (myDataGridView.Rows.Count > 0) { int i = myDataGridView.ColumnHeadersHeight;//标题行高 int j = myDataGridView.Rows.GetRowsHeight(DataGridViewElementStates.Visible); //所有可见行总高 int k = myDataGridView.Height; //控件高度 int l = myDataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible);//最后一行索引 int count = myDataGridView.Columns.Count;//列总数 int width = 0; //当网格未充满控件时才画线 if (i + j < k) { using (Brush gridBrush = new SolidBrush(myDataGridView.GridColor)) { using (Pen gridLinePen = new Pen(gridBrush)) { //处理标题列 if (myDataGridView.RowHeadersVisible) { width = myDataGridView.RowHeadersWidth; e.Graphics.DrawLine(gridLinePen, width, i + j, width, k); } else { width = 1; } //处理正常列 for (int index = 0; index < count; index++) { if (myDataGridView.Columns[index].Visible) { width += myDataGridView.Columns[index].Width; e.Graphics.DrawLine(gridLinePen, width, i + j, width, k); } } } } } } }
11.判断有无滚动条
//垂直滚动条 if (dataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.None) > dataGridView1.Height) MessageBox.Show("有"); else MessageBox.Show("无"); //水平滚动条 if(dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.None) > dataGridView1.Width) MessageBox.Show("有"); else MessageBox.Show("无");
12.为什么列标题总不居中?
已经将列标题默认对齐方式设置为居中:
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示
但实际的效果总是偏左了一点,原因是列可以进行排序,排序标志符号在列标题上占了空间。逐列按下边设置可去掉:
for (int i = 0; i < dataGridView1.Columns.Count; i++) { dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; }