如何使datagridview行文本在粗体当我选择一行
本文关键字:选择 一行 datagridview 何使 文本 | 更新日期: 2023-09-27 18:10:40
当我选择一行时,如何使datagridview行文本以粗体显示?
处理DataGridView的CellFormatting事件,如果单元格属于选定行,则对字体应用加粗样式:
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);
// edit: to change the background color:
e.CellStyle.SelectionBackColor = Color.Coral;
}
}
在Datagrid中加载内容后,将这些事件处理程序应用于RowEnter和RowLeave。
private void dg_RowEnter(object sender, DataGridViewCellEventArgs e)
{
System.Windows.Forms.DataGridViewCellStyle boldStyle = new System.Windows.Forms.DataGridViewCellStyle();
boldStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
dg.Rows[e.RowIndex].DefaultCellStyle = boldStyle;
}
private void dg_RowLeave(object sender, DataGridViewCellEventArgs e)
{
System.Windows.Forms.DataGridViewCellStyle norStyle = new System.Windows.Forms.DataGridViewCellStyle();
norStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular);
dg.Rows[e.RowIndex].DefaultCellStyle = norStyle;
}
代码没有被测试。但是应该没问题。
希望能有所帮助。
尝试处理dataGridView的SelectionChanged
事件并设置cell
样式
下面的代码将使选定行的字体为粗体样式。"Total"是我代码中的最后一行检查
protected void gvRow_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[rowIndex].Text == "Total")
{
e.Row.Font.Bold = true;
}
}
}