C# DataGridView 选中的单元格样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1050364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataGridView selected cell style
提问by Yanko Hernández Alvarez
How can I change the "selection style" on a DataGridView (winforms)?
如何更改 DataGridView (winforms) 上的“选择样式”?
采纳答案by Luis
You can easily change the forecolor and backcolor of selcted cells by assigning values to the SelectedBackColor and SelectedForeColor of the Grid's DefaultCellStyle.
您可以通过为网格的 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
};
}
}
回答by Matthew Jones
Use the SelectedCells propertyof the GridView and the Style propertyof the DataGridViewCell.
使用GridView的SelectedCells 属性和DataGridViewCell的Style 属性。
回答by BFree
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;
}
}
回答by Nate B.
回答by Alejandro del Río
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;
}
}
}