问题描述
我有一个动态绑定到 datatable
的 datagridiview
.我想将标题中的某些列右对齐.
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.
我为 cellstyle 和 headercell 的 datagridview
尝试了此设置.对于单元格样式,它显示正确,但对于标题,它不是:
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;
有人可以帮我吗?
推荐答案
代码有效:您在标题文本右侧看到的空间是正常的".
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
属性设置为 NotSortable.这将防止为排序字形保留空间.
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 中右对齐一列不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!