c# - 右对齐 datagridview 中的列不起作用

标签 c# winforms datagridview

我有一个动态绑定(bind)到 datatabledatagridiview。我想将标题中的一些列右对齐。

我为 cellstyle 和 headercell 的 datagridview 尝试了这个设置。对于单元格样式,它显示正确但对于标题它不是:

enter image description here

我使用的代码:

this.dataGridView1.Columns["Quantity"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

谁能帮帮我?

最佳答案

代码有效:您在标题文本右侧看到的空间是“正常的”。

DataGridView 支持按列排序。因此,每个列标题都保留了足够的空间来显示排序字形(通常是箭头)。

如果您希望列标题中的文本完全右对齐,您需要禁用排序。将列的 SortMode 属性设置为 NotSortable。这将防止为排序字形保留空间。

实物课:

public class FrmTest : Form
{

    public FrmTest()
    {
        InitializeComponent();

        this.DataGridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
        this.DataGridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
    }

    private void CheckBox1_CheckedChanged(System.Object sender, System.EventArgs e)
    {
        if (this.CheckBox1.Checked) {
            this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
        } else {
            this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
        }
        this.DataGridView1.Refresh();
    }
}

1/加载表单后:

enter image description here

2/通过点击复选框允许排序:

enter image description here

3/点击列后:

enter image description here

关于c# - 右对齐 datagridview 中的列不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17404969/

相关文章:

c# - 我们已将 VB6 代码迁移到 .net 中的 C#

c# - 向 Windows 窗体消息循环发送或发布消息

.net - 您在 UI 中使用 System.Component.BackgroundWorker 的频率如何? (如果曾经)

c# - 尝试查询数据库时收到错误 "no database selected"

.Net 在运行时重新排序 DataGridView 列

c# - DataGridView:如何选择整个列并取消选择其他所有内容?

c# - 使用 .NET 和 Canvas 应用程序的 facebook api 获取 CanvasUrl 为空或为空

C# visual studio 如何重新定位 nuget 包文件夹?

c# - 向上或向下移动树中的节点

c# - 如何将文件从特定文件夹复制到 C# 中的共享文件夹?