修正DataGridView的列乱序的问题

当DataGridView控件绑定到数据源时,列的显示顺序可能与设计时不一致。本文介绍了一个解决方案,通过使用DataGridViewColumn类的DisplayIndex属性手动调整列的显示顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在DataGridView的设计时,在设计器中增加了多个列绑定,显示时也都能显示出来,但经常碰到的问题是:在设计时的列顺序和运行时的列顺序不一样

这是因为将 Windows 窗体 DataGridView 控件绑定到数据源时,自动生成的列的显示顺序由数据源确定,而没有完全根据设计器的顺序,算是vs的一个bug

如果不希望以这种顺序显示,可以通过使用 DataGridViewColumn 类的 DisplayIndex 属性更改列的显示顺序。例如

 
 
private   void  AdjustColumnOrder()
{
    customersDataGridView.Columns[
"CustomerID"].Visible = false;
    customersDataGridView.Columns[
"ContactName"].DisplayIndex = 0;
    customersDataGridView.Columns[
"ContactTitle"].DisplayIndex = 1;
    customersDataGridView.Columns[
"City"].DisplayIndex = 2;
    customersDataGridView.Columns[
"Country"].DisplayIndex = 3;
    customersDataGridView.Columns[
"CompanyName"].DisplayIndex = 4;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值