在显示表单之前/在窗体显示时在 DataGridView 上设置单元格字体

本文关键字:显示 设置 单元格 字体 DataGridView 窗体 表单 | 更新日期: 2023-09-27 18:31:52

Background

当我点击 WinForm 上的按钮时,我正在将数据加载到 BindingSource 中,该 BindingSource 用作 DataGridView 的数据源。 加载数据后,我会对 DataGridView 进行一些修改;特别是,I 1) 将任何值为 DBNull 的单元格设置为字符串值"NULL",2) 斜体相同的单元格,以及 3) 突出显示某些行。

我正在做的事情的简单例子:

private void btnFetch_Click(object sender, EventArgs e)
{
    // If there's already a DataSource, Dispose of it.
    if (bsMessageTracking.DataSource != null)
    {
        (bsMessageTracking.DataSource as DataTable).Dispose();
    }
    // Get new DataSource.
    bsMessageTracking.DataSource = GetDataTable(); // Details not relevant.
    // Show NULL values.
    foreach (DataGridViewRow row in dgv.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.Value is DBNull)
            {
                cell.Value = "NULL";
                cell.Style.Font = new Font(dgv.DefaultCellStyle.Font, FontStyle.Italic);
            }
        }
    }
    // Apply highlighting.
    foreach (DataGridViewRow row in dgvMessageTracking.Rows)
    {
        if (HighlightRow(row)) // Details not relevant.
        {
            row.DefaultCellStyle.BackColor = Color.LightYellow;
        }
    }
}

数据根据输入到窗体上的文本框中加载。

情况

如果这发生在按钮单击时,一切正常。 但是,为了向用户提供一些便利,我允许此窗体加载预填充的数据 - 主窗体将使用要放入 TextBox 的数据实例化此窗体,并且此btnFetch_Click处理程序将从构造函数调用:

internal MessageTracking(string ID)
{
    InitializeComponent();
    // Setup data source.
    dgvMessageTracking.DataSource = bsMessageTracking;
    // Set ID and run query.
    if (ID != null)
    {
        // Set ID.
        txtlID.Text = ID;
        // Run!
        btnFetch_Click(null, null);
    }
}

单元格的值发生了变化(所以我看到 NULL),但字体和突出显示不会粘住。

我尝试过什么

如果我在 OnShow 方法中复制突出显示代码,突出显示会粘住。 但是,在那里复制字体代码不起作用。 如果我将字体放在 CellFormatting 中,我可以使字体粘住,但这对我来说似乎有点矫枉过正,因为我只需要在加载表单时运行一次 - 如果在表单可见运行进程,它可以正常工作。

辩解

如果有人有任何建议,我将不胜感激。 谢谢!

在显示表单之前/在窗体显示时在 DataGridView 上设置单元格字体

对于您正在使用的事件处理程序,我建议使用 dataGridView Cell_Formatting,如 @zimdanen。但是,这是我如何使它工作。

    private void small8PtToolStripMenuItem_Click(object sender, EventArgs e)
    {
        fontSize = 8;
        dataGridBatchHistory.Refresh();
    }

fontSize 是我用来动态设置字体的整数,您可以通过这种方式设置大多数属性。 而不是我调用我的单元格格式化函数

    private void dataGridBatchHistory_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        e.CellStyle.Font = new Font("Tahoma", fontSize);
    }

这将在单击"我的工具行程"菜单项时以新的正确大小更新我的表单。 但是我相信这适用于您可以创建的许多事件!

我想

,由于缺乏响应,如果您希望表单首次可见时显示格式,没有更好的方法。 我已经删除了btnFetch_Click处理程序的Show NULL values部分,并添加了此dgvMessageTracking_CellFormatting处理程序以始终处理此功能:

private void dgvMessageTracking_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.Value is DBNull)
    {
        e.Value = "NULL";
        e.CellStyle.Font = new Font(dgvMessageTracking.DefaultCellStyle.Font, FontStyle.Italic);
    }
}