简体   繁体   中英

Not able to hide first column in datagridview?

I have a datagridview in a windows form which contains some columns. And I want to hide the Ist column( CompanyID ) through the code behind.

But Ist column is not hiding.

Have tried below 2 things :

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.

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.

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.

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.

Set autogenerate columns to false and then add each column one by one to the grid. Then set the column you don't want to see to visible = false. No need for code behind.

Try this:

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#:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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