c# Winforms DataGridView粗体样式行

本文关键字:样式 Winforms DataGridView | 更新日期: 2023-09-27 18:01:49

为什么行中没有文本?如何使文本在行粗体?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Add(new DataGridViewColumn { HeaderText = "Test", CellTemplate = new DataGridViewTextBoxCell() { }, DefaultCellStyle = new DataGridViewCellStyle { Font = new Font("Tahoma", 9.75F, FontStyle.Bold) } });
            this.dataGridView1.DataSource = new List<Employee> 
            { 
                 new Employee {Name="Test"},
                 new Employee {Name="Test"},
                 new Employee {Name="Test"},
                 new Employee {Name="Test"},
                 new Employee {Name="Test"},
                 new Employee {Name="Test"},
                 new Employee {Name="Test"}
            };
        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Number { get; set; }
    }
}

c# Winforms DataGridView粗体样式行

您的列缺少DataPropertyName属性。

获取或设置DataGridViewColumn绑定到的数据源属性或数据库列的名称。

改成:

this.dataGridView1.Columns.Add(new DataGridViewColumn { 
    HeaderText = "Test", 
    DataPropertyName = "Name", 
    CellTemplate = new DataGridViewTextBoxCell() { }, 
    DefaultCellStyle = new DataGridViewCellStyle { Font = new Font("Tahoma", 9.75F, FontStyle.Bold), ForeColor = Color.Black } 
});

添加加粗字体的行

public Form1()
{
    InitializeComponent();
    BindingList<Employee> list = new BindingList<Employee>();
    list.Add(new Employee() { Name = "Test1" });
    list.Add(new Employee() { Name = "Test2" });
    list.Add(new Employee() { Name = "Test3" });
    list.Add(new Employee() { Name = "Test4" });
    list.Add(new Employee() { Name = "Test5" });
    dataGridView1.DataSource = list;
}