[英]DataGridView selected cell style
如何更改DataGridView(winforms)上的“选择样式”?
You can easily change the forecolor and backcolor of selcted cells by assigning values to the SelectedBackColor and SelectedForeColor of the Grid's DefaultCellStyle. 通过将值分配给Grid的DefaultCellStyle的SelectedBackColor和SelectedForeColor,您可以轻松更改选定单元格的前景色和背景色。
If you need to do any further styling you you need to handle the SelectionChanged event 如果您需要进行任何进一步的样式设置,则需要处理SelectionChanged事件
Edit: (Other code sample had errors, adjusting for multiple selected cells [as in fullrowselect]) 编辑:(其他代码示例有错误,调整多个选定单元格[如在fullrowselect中])
using System.Drawing.Font;
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach(DataGridViewCell cell in ((DataGridView)sender).SelectedCells)
{
cell.Style = new DataGridViewCellStyle()
{
BackColor = Color.White,
Font = new Font("Tahoma", 8F),
ForeColor = SystemColors.WindowText,
SelectionBackColor = Color.Red,
SelectionForeColor = SystemColors.HighlightText
};
}
}
使用GridView的SelectedCells属性和DataGridViewCell的Style属性 。
Handle the SelectionChanged event on your DataGridView and add code that looks something like this: 处理DataGridView上的SelectionChanged事件并添加如下所示的代码:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
foreach (DataGridViewCell c in row.Cells)
{
c.Style = this.dataGridView1.DefaultCellStyle;
}
}
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.Red;
style.Font = new Font("Courier New", 14.4f, FontStyle.Bold);
foreach (DataGridViewCell cell in this.dataGridView1.SelectedCells)
{
cell.Style = style;
}
}
With this you can even draw a colored border to the selected cells. 有了这个,您甚至可以为选定的单元格绘制彩色边框。
private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected == true)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Border);
using (Pen p = new Pen(Color.Red, 1))
{
Rectangle rect = e.CellBounds;
rect.Width -= 2;
rect.Height -= 2;
e.Graphics.DrawRectangle(p, rect);
}
e.Handled = true;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.