[英]Change font size in a column in DataGridView
我在 DataGridView(WinForm 应用程序)中有一个需要更改字体大小和样式的列。 从这里的文章: http : //msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx ,我想下面的代码会得到我想要的结果(我是首先通过更改样式进行测试):
this.dataGridViewMain.Columns[3].DefaultCellStyle.Font = new Font(dataGridViewMain.DefaultCellStyle.Font, FontStyle.Italic);
但是代码不会改变任何东西。 我还尝试在RowPostPaint
事件处理程序上添加代码,但仍然不起作用。 我知道程序使用的字体是在DataGridView.RowsDefaultCellStyle
属性上设置的,但我认为在RowPostPaint
事件中放置代码会覆盖它。 下面是来自RowPostPaint
事件的代码:
void dataGridViewMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
this.dataGridViewMain.Columns[3].DefaultCellStyle.BackColor = Color.Gray;
foreach (DataGridViewRow row in this.dataGridViewMain.Rows)
{
int daysInShop = Convert.ToInt32(row.Cells["Days in the shop"].Value);
if (daysInShop > 4)
{
row.DefaultCellStyle.BackColor = Color.Red;
row.DefaultCellStyle.ForeColor = Color.White;
}
else if (daysInShop > 2)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else
{
row.DefaultCellStyle.BackColor = Color.YellowGreen;
}
row.Height = 35;
}
this.dataGridViewMain.CurrentCell = null; // no row is selected when DGV is displayed
}
任何帮助表示赞赏。 谢谢。
好的,这就是我发现的。 在InitializeComponent()
有这一行:
dataGridViewCellStyle3.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
当我注释掉该行时,将RowPostPaint
的列斜体化的代码工作正常。 然后我在RowPostPaint
添加了下面的代码,以便其他列字体为粗体且尺寸更小。 我仍然不太确定为什么DataGridView.Columns[colNumber].DefaultCellStyle.Font
不会覆盖dataGridViewCellStyle3
int colCount = dataGridViewMain.ColumnCount;
for (int i = 0; i < colCount; i++)
{
if(i != 3)
this.dataGridViewMain.Columns[i].DefaultCellStyle.Font = new System.Drawing.Font("Verdana", 14F, FontStyle.Bold);
else
this.dataGridViewMain.Columns[3].DefaultCellStyle.Font = new System.Drawing.Font("Verdana", 25F, FontStyle.Bold);
}
字体大小是只读的,因此您需要创建新字体并设置 yourDataGridView.Font = new Font(name,size,style) 这里是更多信息: http : //msdn.microsoft.com/en-us/library/ system.drawing.font.aspx
在InitializeComponent()
之后将RowsDefaultCellStyle
设置为null
。
我认为DataGridView
以网格/列/行的顺序采用样式。 因此,如果设置了行样式,它总是会覆盖任何列样式。
在我看来,这是一个糟糕的设计——根本不需要默认的行样式!
试试这个:
foreach (DataGridViewRow dr in dataGridView.Rows)
{
if ( // your condition here )
{
dr.Cells[0].Style.Font = new Font( dataGridView.Font, FontStyle.Underline);
dr.Cells[0].Style.ForeColor = Color.White;
dr.Cells[0].Style.BackColor = Color.Red;
}
else
{
// It also may be a good idea to restore original settings
// for the non selected rows just in case you re run this routine
dr.Cells[0].Style.BackColor = dataGridView.Columns[0].DefaultCellStyle.BackColor;
dr.Cells[0].Style.ForeColor = dataGridView.Columns[0].DefaultCellStyle.ForeColor;
dr.Cells[0].Style.Font = dataGridView.Columns[0].DefaultCellStyle.Font;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.