简体   繁体   English

无法隐藏datagridview中的第一列?

[英]Not able to hide first column in datagridview?

I have a datagridview in a windows form which contains some columns. 我在Windows窗体中有一个datagridview ,其中包含一些列。 And I want to hide the Ist column( CompanyID ) through the code behind. 我想通过后面的代码隐藏Ist列( CompanyID )。

But Ist column is not hiding. 但是Ist列并未隐藏。

Have tried below 2 things : 尝试了以下2件事:

dgvVendorDetails.Columns["CompanyID"].Visible = false;

And: 和:

dgvVendorDetails.Columns[0].Visible = false;

I don't know the reason behind this. 我不知道背后的原因。 I have searched a lot but got no solution. 我已经搜索了很多,但没有解决方案。

Both of these syntax are corrects and should work: 这两种语法都是正确的,应该可以工作:

dgvVendorDetails.Columns["CompanyID"].Visible = false;
dgvVendorDetails.Columns[0].Visible = false;

My guess is that you are using the DataGridView.AutoGenerateColumns functionnality and even if you set the DataSource property, the DatagridView won't create columns until the grid is displayed. 我的猜测是您正在使用DataGridView.AutoGenerateColumns函数,即使您设置了DataSource属性, DatagridView也不会在显示网格之前创建列。

So it's possible that: 因此有可能:

  • you try to access columns that do not exist yet (but the code should raise an exception) 您尝试访问尚不存在的列(但代码应引发异常)
  • or you access valid columns, but they are replaced when the grid is bound again and so your code has no effect (probably your case since you do not mention an exception). 或者您访问有效的列,但是当再次绑定网格时它们将被替换,因此您的代码无效(可能是您的情况,因为您没有提及异常)。

If so, the solution is to use the DataBindingComplete Event. 如果是这样,解决方案是使用DataBindingComplete事件。

See also these related issues: 另请参阅以下相关问题:

EDIT 编辑

As @brikovich pointed out, another solution is not not use the AutoGenerated columns but create them and configure them at design time or at runtime. 正如@brikovich指出的,另一种解决方案不是不使用AutoGenerated列,而是在设计时或运行时创建并配置它们。

This thread How to select visible columns in Datagridview bound to DataTable can help you to achieve this and/or make a choice between these two options. 此线程如何在绑定到DataTable的Datagridview中选择可见列可以帮助您实现这一点和/或在这两个选项之间进行选择。

Set autogenerate columns to false and then add each column one by one to the grid. 将自动生成的列设置为false,然后将每一列一一添加到网格中。 Then set the column you don't want to see to visible = false. 然后将您不希望看到的列设置为visible = false。 No need for code behind. 无需后面的代码。

Try this: 尝试这个:

VB.net: VB.net:

    Private Sub dgvVendorDetails_ColumnAdded(sender As Object, e As DataGridViewColumnEventArgs) Handles dgvVendorDetails.ColumnAdded
        If e.Column.Name = "CompanyID" Then dgvVendorDetails.Columns("CompanyID").Visible = False
    End Sub

C#: C#:

private void dgvVendorDetails_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    if (e.Column.Name == "CompanyID")
        dgvVendorDetails.Columns("CompanyID").Visible = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM