Search code examples
c#winformsfontsdatagridviewembedded-resource

Adding an embedded font to a datagridview


I want to put a custom font to a datagridview but it is not applied, it only applies to other elements such as labels.

I originally tried this and it worked as expected.

fontCollection.AddFontFile("./Resources/Circulitos.ttf");

But then I wanted to try with an embedded file and the font is not displayed correctly in the datagridview, however it is displayed correctly in a label that I have for testing. This is the code I have:

program.cs

internal static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>

    static private List<PrivateFontCollection> _fontCollections;

    [STAThread]
    static void Main()
    {
        // To customize application configuration such as set high DPI settings or default font,
        // see https://aka.ms/applicationconfiguration.
        ApplicationConfiguration.Initialize();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(true);
        Application.ApplicationExit += delegate {
            if (_fontCollections != null)
            {
                foreach (var fc in _fontCollections) if (fc != null) fc.Dispose();
                _fontCollections = null;
            }
        };
        Application.Run(new Main());
    }
    static public Font GetCustomFont(byte[] fontData, float size, FontStyle style)
    {
        if (_fontCollections == null) _fontCollections = new List<PrivateFontCollection>();
        PrivateFontCollection fontCol = new PrivateFontCollection();
        IntPtr fontPtr = Marshal.AllocCoTaskMem(fontData.Length);
        Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
        fontCol.AddMemoryFont(fontPtr, fontData.Length);
        Marshal.FreeCoTaskMem(fontPtr);
        _fontCollections.Add(fontCol);
        return new Font(fontCol.Families[0], size, style);
    }
}

Main.cs

public partial class Main : Form
{  
    private PrivateFontCollection fontCollection;
    private Font gf;

    public Main()
    {
        gf = Program.GetCustomFont(Properties.Resources.Circulitos, 10, FontStyle.Regular);
        InitializeComponent();
    }
    private void circulitos(int index, bool update)
    {
        dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Green;
        dataGridView1.DefaultCellStyle.Font = gf;
        dataGridView1.ColumnHeadersDefaultCellStyle.Font = gf;
        dataGridView1.RowHeadersDefaultCellStyle.Font = gf;
        dataGridView1.EnableHeadersVisualStyles = false;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCell cell = row.Cells[1];
            try
            {
                cell.Style.Font = gf;
            }
            catch
            {
                MessageBox.Show("Error fontCollection");
            }
            label5.Font = gf;
        }
        dataGridView1.Refresh();
        dataGridView1.Invalidate();
    }  
}

What can I do to make the font apply to the cells of a datagridview and not just to the labels? Thanks for your time


Solution

  • Main.cs

    private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.RowIndex >= 1 && e.ColumnIndex >= 0)
        {
            e.Handled = true;
            e.PaintBackground(e.CellBounds, true);
            e.Graphics.DrawString(e.FormattedValue.ToString(), customFont, Brushes.Black, e.CellBounds, StringFormat.GenericDefault);
            e.Paint(e.CellBounds, DataGridViewPaintParts.Border);
        }
    }