右对齐datagridview中的列不起作用 [英] Right align a column in datagridview doesn't work
问题描述
我有一个 datagridiview
,它动态绑定到一个 datatable
。我想将标题中的一些列对齐。
I am having a datagridiview
which is dynamically bound to a datatable
. I would like to align some of the columns in header to right aligned.
我尝试过这个设置,用于 datagridview
用于cellstyle和headercell。对于单元格样式,它显示正确,但标题不是:
I tried this setting for the datagridview
for both cellstyle and headercell. For cell style it is showing correctly but for header it is not:
我使用的代码:
this.dataGridView1.Columns["Quantity"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
有些人可以帮助我吗?
推荐答案
代码的作品:您在标题文本右侧看到的空格是normal。
The code works: the space you see at the right of the header text is "normal".
DataGridView
支持按列排序。因此,每个列头都保留足够的空间来显示排序字形(通常是一个箭头)。
The DataGridView
supports sorting by columns. Therefore, each column header reserves enough space to display the sort glyph (usually an arrow).
如果您希望列标题中的文本完美右对齐,你需要禁用排序。将列的 SortMode
属性设置为不可选。这将防止为排序字形保留空格。
If you want the text in column header to be perfectly right aligned, you'll need to disable sorting. Set the SortMode
property for the column to NotSortable. This will prevent space from being reserved for the sort glyph.
对象课程:
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 /加载表单后:
2 /通过点击复选框允许排序:
2/ Allow sorting by clicking the checkbox:
3 /点击列后:
这篇关于右对齐datagridview中的列不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!