How do I test a DataGridView cell to see if font style is bold?

Saga 431 Reputation points
2021-11-18T20:56:52.643+00:00

Hi all,

I am traversing through the cells in a DataGridView row to print them. I need to determine whether the font style in the cell is bold. How can I do this?

The code follows:

foreach (DataGridViewCell Cel in GridRow.Cells)
   {
      if (Cel.Value != null)
        {

           //This is always false.
           if (Cel.InheritedStyle.Font.Bold)
               fontPrint = fontPrintBold;
           else
               fontPrint = new Font("Ariel", 11, FontStyle.Regular);

           e.Graphics.DrawString(Cel.Value.ToString(),
               //Cel.InheritedStyle.Font,
               fontPrint,
               new SolidBrush(Cel.InheritedStyle.ForeColor),
               new RectangleF((int)arrColumnLefts[iCount],
               (float)iTopMargin,
               (int)arrColumnWidths[iCount], (float)iCellHeight),
               strFormat);
        }

      iCount++;
   }

I also tried using

Cel.Style.Font.Bold

However, this gives a null reference exception. I am trying to print bold font whenever the text in the cell is bold.

Any orientation is appreciated. Thank you, Saga

Developer technologies | C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-11-19T01:03:16.877+00:00

    See if you can adapt the following to your task. Currently it's checking column index 0 but you can modify to do all cells.

    150729-figure1.png

    using System;  
    using System.Reflection;  
    using System.Windows.Forms;  
      
    namespace WindowsFormsSample  
    {  
        public static class DataGridViewColumnExtensions  
        {  
            public static DataGridViewCellStyle GetFormattedStyle(this DataGridViewCell cell)  
            {  
                var dgv = cell.DataGridView;  
      
                if (dgv == null)  
                {  
                    return cell.InheritedStyle;  
                }  
      
                var formattingArgs = new DataGridViewCellFormattingEventArgs(  
                    cell.ColumnIndex,   
                    cell.RowIndex,   
                    cell.Value,   
                    cell.FormattedValueType,   
                    cell.InheritedStyle);  
      
                var methodInfo = dgv.GetType().GetMethod("OnCellFormatting",  
                    BindingFlags.Instance | BindingFlags.NonPublic,  
                    null,  
                    new Type[] { typeof(DataGridViewCellFormattingEventArgs) },  
                    null);  
      
                methodInfo.Invoke(dgv, new object[] { formattingArgs });  
                return formattingArgs.CellStyle;  
            }  
        }  
    }  
    

    Form code, the column is defined in the designer.

    using System;  
    using System.Drawing;  
    using System.Windows.Forms;  
      
    namespace WindowsFormsSample  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
      
                dataGridView1.CellFormatting += DataGridView1OnCellFormatting;  
            }  
      
            private void DataGridView1OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)  
            {  
                if (e.ColumnIndex != 0) return;  
      
                if (Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[0].Value) == "Anne")  
                {  
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.DarkSalmon;  
                    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);  
                }  
                else  
                {  
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Empty;  
                    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Regular);  
                }  
            }  
              
            private void Form1_Load(object sender, EventArgs e)  
            {  
                dataGridView1.Rows.Add("Karen");  
                dataGridView1.Rows.Add("Anne");  
                dataGridView1.Rows.Add("Karen");  
                dataGridView1.Rows.Add("Anne");  
                dataGridView1.Rows.Add("Mary");  
                dataGridView1.Rows.Add("Anne");  
            }  
      
            private void IterateRowsButton_Click(object sender, EventArgs e)  
            {  
                  
                listBox1.Items.Clear();  
      
                for (int index = 0; index < dataGridView1.Rows.Count -1; index++)  
                {  
                      
                    if (dataGridView1.Rows[index].IsNewRow)  
                    {  
                        continue;  
                    }  
      
                    var cellStyle = dataGridView1.Rows[index].Cells[0].GetFormattedStyle();  
                    listBox1.Items.Add(cellStyle.Font.Bold ? $"{index} is bold" : $"{index} is not bold");  
                }  
                  
            }  
        }  
    }  
      
    

1 additional answer

Sort by: Most helpful
  1. Tom Edell 1 Reputation point
    2021-11-18T23:56:43.293+00:00

    I'm not sure if this work, but if you verify that your Class starts with something like this:
    Imports System.Drawing
    Imports System.Windows.Forms

    Public Class Form1
    Inherits System.Windows.Forms.Form
    Private WithEvents dvgData As New DataGridView
    .....

    Then something like:
    Private Sub dvgData_CellFormatting(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
    Handles dvgData.CellFormatting

    .....

    If you want to change the font in a whole column, you could try something like this:
    With dvgData
    .Name = "dvgData"
    .Columns(0).DefaultCellStyle.Font = _
    New Font(dvgData.DefaultCellStyle.Font, FontStyle.Bold)
    .....

    A few last words...
    I think the best stable solution is to create a new Font instance, specifically directed to the column, row or cell you whish to change.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.