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