.net 如何在 DataGridView 列中右对齐文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5230316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:20:46  来源:igfitidea点击:

How can I right-align text in a DataGridView column?

.netwinformsdatagridviewdatagridviewcolumn

提问by Jayantha Lal Sirisena

How can I right-align text in a DataGridView column? I am writing a .NET WinForms application.

如何在 DataGridView 列中右对齐文本?我正在编写一个 .NET WinForms 应用程序。

回答by MUG4N

this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 

回答by zDougie

I know this is old, but for those surfing this question ... the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptible. Instead I used:

我知道这是旧的,但是对于那些浏览这个问题的人...... MUG4N 的答案将对齐所有使用相同 defaultcellstyle 的列。我没有使用 autogeneratecolumns 所以这是不可接受的。相反,我使用了:

e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

e in this case is from:

在这种情况下,e 来自:

Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)  

回答by daniele3004

To set align text in dataGridCell you have two ways:

要在 dataGridCell 中设置对齐文本,您有两种方法:

Set the align for a specific cell or set for each cell of row.

为特定单元格设置对齐方式或为行的每个单元格设置对齐方式。

For one column go to Columns->DataGridViewCellStyle

对于一列去 Columns->DataGridViewCellStyle

or

或者

For each column go to RowDefaultCellStyle

对于每一列去 RowDefaultCellStyle

The control panel is the same as the follow:

控制面板如下所示:

enter image description here

在此处输入图片说明

回答by Sayed Muhammad Idrees

you can edit all the columns at once by using this simple code via Foreach loop

您可以通过 Foreach 循环使用此简单代码一次编辑所有列

        foreach (DataGridViewColumn item in datagridview1.Columns)
        {
            item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        }