C#众datagridview
时间: 2025-06-05 12:45:07 浏览: 12
### C# 中 DataGridView 控件的使用指南
#### 1. 基本功能设置
DataGridView 是 Windows Forms 应用程序中的一个重要控件,用于显示表格数据。可以通过多种方式自定义其外观和行为。
以下是设置基本属性的一个示例:
```csharp
dataGridView1.DataSource = dataTable; // 绑定 DataTable 数据源
dataGridView1.ReadOnly = true; // 设置只读模式
dataGridView1.AllowUserToAddRows = false; // 禁止手动添加行
dataGridView1.RowHeadersVisible = false; // 隐藏行头
```
#### 2. 自定义单元格样式
可以调整单元格的颜色、字体和其他视觉效果来增强用户体验。例如:
```csharp
dataGridView1.DefaultCellStyle.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.LightGray;
dataGridView1.EnableHeadersVisualStyles = false; // 关闭默认表头样式以便应用自定义颜色
```
#### 3. 移除选中状态高亮
如果希望隐藏用户点击某一行或某一列后的突出显示效果,则可按照以下方法操作[^2]:
```csharp
dataGridView1.DefaultCellStyle.SelectionBackColor = dataGridView1.DefaultCellStyle.BackColor;
dataGridView1.DefaultCellStyle.SelectionForeColor = dataGridView1.DefaultCellStyle.ForeColor;
```
此代码片段会使得即使某个单元格被选定,它的背景色也不会发生变化。
#### 4. 实现打印功能
为了实现打印功能,通常需要处理 PrintPage 事件并绘制网格内容到打印机页面上。下面是一个简单的例子展示如何完成这一目标[^1]:
```csharp
private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int i = 0, j = 0;
float rowHeight = 0f;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow && i < rowsPerPage) // 跳过新行以及超出当前页数的部分
{
for (j = 0; j < dataGridView1.Columns.Count; ++j)
{
RectangleF cellBounds = GetCellPrintBounds(j, i);
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Near;
Brush brush = Brushes.Black;
string text = dataGridView1.Rows[i].Cells[j].FormattedValue.ToString();
e.Graphics.DrawString(text, dataGridView1.Font,
brush, cellBounds.Location.X, cellBounds.Location.Y + rowHeight, sf);
}
rowHeight += dataGridView1.Rows[i].Height;
i++;
}
}
}
// 辅助函数获取每个单元格的位置边界
private RectangleF GetCellPrintBounds(int colIndex, int rowIndex)
{
Rectangle rect = dataGridView1.GetCellDisplayRectangle(colIndex, rowIndex, true);
return new RectangleF(rect.X * scaleRatioX, rect.Y * scaleRatioY, rect.Width * scaleRatioX, rect.Height * scaleRatioY);
}
```
以上代码展示了如何遍历 `DataGridView` 的每一项并将它们逐个渲染至打印文档之中。
---
阅读全文
相关推荐


















