在默認情況下,datagridview的顯示效果:
1.禁用最後一行空白。
默認情況下,最後一行空白表示自動新增行,對於需要在控件中進行編輯,可以保留
dataGridView1.AllowUserToAddRows = false;
上述禁用,僅是將用戶界面交互的自動新增行禁了,但還是可以通過代碼:dataGridView1.Rows.Add();來新增一行空白。
2.禁用‘delete’鍵的刪除功能。
默認情況,鼠標選中一整行,按 刪除鍵 可以刪除當前一整行
dataGridView1.AllowUserToDeleteRows = false;
上述禁用,僅是將用戶界面交互的自動新增行禁了,但還是可以通過代碼:
dataGridView1.Rows.Remove(DataGridViewRow dataGridViewRow);
或者
dataGridView1.Rows.RemoveAt(int index);
來刪除指定行數據。
3.啓用鼠標拖拽列功能
啓用後,可以通過鼠標拖拽,對列的順序進行重排序。但是拖拽不會影響各列通過代碼訪問時的列序號(保持原來的序號),只是展示效果變化。
dataGridView1.AllowUserToOrderColumns = true;
4.禁用鼠標拖動行高度、列寬度
禁用後,不能通過鼠標交互改變列的寬度和行的高度。不影響通過代碼設置
dataGridView1.AllowUserToResizeColumns = false; // 禁拖動列寬度
dataGridView1.AllowUserToResizeRows = false; // 禁拖動行高度
5.禁用鼠標拖動行標題(最左側空白列)寬度
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; // 枚舉,可以枚舉位自適應大小
6.禁用單元格編輯功能
dataGridView1.ReadOnly = true;
7.點擊選中整行、整列
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;// 單擊選中整行,枚舉
SelectionMode 爲枚舉類型:
CellSelect 可以選定一個或多個單元格
FullRowSelect 通過單擊行的標頭或是該行所包含的單元格選定整個行
FullColumnSelect 通過單擊列的標頭或該列所包含的單元格選定整個列
RowHeaderSelect 通過單擊行的標頭單元格選定此行。 通過單擊某個單元格可以單獨選定此單元格。
ColumnHeaderSelect 可以通過單擊列的標頭單元格選定此列。 通過單擊某個單元格可以單獨選定此單元格。
8.禁用多行/多列/多單元格選擇
dataGridView1.MultiSelect = false;
9.設置表格網格線顏色等樣式
dataGridView1.AdvancedCellBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble; // 設置邊框樣式(上邊框),枚舉:雙線內陷邊框
// ...
dataGridView1.GridColor = Color.SeaGreen; //邊框線 顏色
10.自動行序號
沒有直接的設置屬性,需要藉助控件渲染事件:
dataGridView1.CellPainting+=dataGridView1_CellPainting;
//在單元格需要繪製時發生。
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; //單位格內數據對齊方式
}
顯示效果: