How can I right-align text in a DataGridView column?
How can I right-align text in a DataGridView column? I am writing a .NET WinForms ap开发者_运维百科plication.
this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
To set align text in dataGridCell you have two ways:
Set the align for a specific cell or set for each cell of row.
For one column go to Columns->DataGridViewCellStyle
or
For each column go to RowDefaultCellStyle
The control panel is the same as the follow:
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 acceptable. Instead I used:
e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
In this case e
is from:
Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
you can edit all the columns at once by using this simple code via Foreach loop
foreach (DataGridViewColumn item in datagridview1.Columns)
{
item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment" Value="Right" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
While we are dealing with alignment and configuration it can be useful to reduce repetitive tasks by using (C#) anonymous types. Much easier to read and advanced operations can be edited in one place. Like in this datagridview dg configuration
foreach (var conf in new [] {
new { Col = 0, WidthPercent = 40, Align = DataGridViewContentAlignment.MiddleCenter } ,
new { Col = 1, WidthPercent = 30, Align = DataGridViewContentAlignment.MiddleCenter } ,
new { Col = 2, WidthPercent = 30, Align = DataGridViewContentAlignment.MiddleCenter }
})
{
dg.Columns[conf.Col].Width = (int)(dg.Width * conf.WidthPercent/100);
dg.Columns[conf.Col].DefaultCellStyle.Alignment = conf.Align;
}
DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;
精彩评论