Reputation: 21366
How can I right-align text in a DataGridView column? I am writing a .NET WinForms application.
Upvotes: 88
Views: 186436
Reputation: 1221
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;
}
Upvotes: 1
Reputation: 1
DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;
Upvotes: -1
Reputation: 121
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)
Upvotes: 6
Reputation: 19
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment" Value="Right" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
Upvotes: 1
Reputation: 1408
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;
}
Upvotes: 3
Reputation: 13880
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:
Upvotes: 14
Reputation: 19717
this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
Upvotes: 143