How to make the selected line font bold in Datagridview?

Asked

Viewed 1,164 times

1

In Datagridview of Windows Forms it is possible to change the font color and background color of the selected line easily using the properties

DataGridView.DefaultCellStyle.SelectionBackColor
DataGridView.DefaultCellStyle.SelectionForeColor

But what about leaving the line selected with the font in bold? I’ve tried a few things like using the event SelectionChanged as follows:

private void Grid_SelectionChanged(object sender, EventArgs e)
{
    var dataGridView = Grid;

    if (dataGridView.SelectedRows.Count > 0)
    {
        var selectedRow = dataGridView.SelectedRows[0];
        selectedRow.DefaultCellStyle.Font = new Font(dataGridView.Font, FontStyle.Bold);
    }            
}

It turns out that it always leaves all the lines with the font in bold, so it’s not quite there.

What’s the right way to do it?

2 answers

1

Try something like that:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  var dataGridView = sender as DataGridView;
  if (dataGridView.Rows[e.RowIndex].Selected)
  {
    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
    e.CellStyle.SelectionBackColor = Color.Coral;
  }
}

0

Good night,

You have tried using the Grid properties ?

Otherwise: Click on the Grid then look in the properties tab on the right side, the properties Rowdefaultcellstyle or Rowtemplate that might solve your problem. So you don’t need to dynamic your code. The properties of the object itself already do this for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.