C#窗体控件DataGridView常用设置

在默认情况下,datagridview的显示效果:

1.禁用最后一行空白。

默认情况下,最后一行空白表示自动新增行,对于需要在控件中进行编辑,可以保留

?
1
dataGridView1.AllowUserToAddRows = false ;

上述禁用,仅是将用户界面交互的自动新增行禁了,但还是可以通过代码:dataGridView1.Rows.Add();来新增一行空白。

2.禁用‘delete'键的删除功能。

默认情况,鼠标选中一整行,按 删除键 可以删除当前一整行

?
1
dataGridView1.AllowUserToDeleteRows = false ;

上述禁用,仅是将用户界面交互的自动新增行禁了,但还是可以通过代码:

?
1
dataGridView1.Rows.Remove(DataGridViewRow dataGridViewRow);

或者

?
1
dataGridView1.Rows.RemoveAt( int index);

来删除指定行数据。

3.启用鼠标拖拽列功能

启用后,可以通过鼠标拖拽,对列的顺序进行重排序。但是拖拽不会影响各列通过代码访问时的列序号(保持原来的序号),只是展示效果变化。

?
1
dataGridView1.AllowUserToOrderColumns = true ;

4.禁用鼠标拖动行高度、列宽度

禁用后,不能通过鼠标交互改变列的宽度和行的高度。不影响通过代码设置

?
1
2
dataGridView1.AllowUserToResizeColumns = false ; // 禁拖动列宽度
dataGridView1.AllowUserToResizeRows = false ; // 禁拖动行高度

5.禁用鼠标拖动行标题(最左侧空白列)宽度

dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; // 枚举,可以枚举位自适应大小 

6.禁用单元格编辑功能

?
1
dataGridView1.ReadOnly = true ;

 7.点击选中整行、整列

?
1
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 单击选中整行,枚举

SelectionMode 为枚举类型:

 

8.禁用多行/多列/多单元格选择

?
1
dataGridView1.MultiSelect = false ;

9.设置表格网格线颜色等样式

?
1
2
3
4
dataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble;
// 设置边框样式(上边框),枚举:双线内陷边框
// ...
dataGridView1.GridColor = Color.SeaGreen; //边框线 颜色

10.自动行序号

没有直接的设置属性,需要借助控件渲染事件:dataGridView1.CellPainting+=dataGridView1_CellPainting;

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//在单元格需要绘制时发生。
   private void dataGridView1_CellPainting( object sender, DataGridViewCellPaintingEventArgs e)
   {
    if (e.ColumnIndex < 0 && e.RowIndex >= 0) // 绘制 自动序号
    {
     e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
     Rectangle vRect = e.CellBounds;
     vRect.Inflate(-2, 2);
     TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), e.CellStyle.Font, vRect, e.CellStyle.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
     e.Handled = true ;
    }
 
    // ----- 其它样式设置 -------
    if (e.RowIndex % 2 == 0)
    { // 行序号为双数(含0)时
     e.CellStyle.BackColor = Color.White;
    }
    else
    {
     e.CellStyle.BackColor = Color.Honeydew;
    }
    e.CellStyle.SelectionBackColor = Color.Gray; // 选中单元格时,背景色
    e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //单位格内数据对齐方式
 
   }

显示效果:

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

文章出处:https://www.jb51.net/article/121045.htm

猜你喜欢

转载自www.cnblogs.com/net-sky/p/9321016.html