【发布时间】:2013-03-15 13:29:37
【问题描述】:
我在 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
}
感谢任何帮助。谢谢。
【问题讨论】:
-
我测试了您的第一个语句以将列更改为斜体,它工作得非常好。请注意,我在已经填充了 datagridview 之后添加了这一点。以前没有。
-
有趣。我已将 DataGridView 上的 RowsDefaultCellStyle 属性设置为 Verdana、14.25pt 和 Bold。这种风格就是出现的。我的斜体列代码不会覆盖该属性。此外,我用 DataTable 填写了 DataGridView,而不是在 DataGridView 中创建自己的列(不确定这是否与问题有关)
-
我也用数据表填充了我的。
-
这是一个相当古老的线程,但偶尔仍然有用。我的小贡献是不需要循环,你可以使用 e->RowIndex 来更加专注,因为你会收到每一行的调用。
-
另外,使用 PrePaint 而不是 PostPaint