Hossein
Hossein

Reputation: 26004

How can I hide a specific column form a dataGridView?

How can I hide a specific Column in DataGridview along with its header while being able to use its value ? ( just doesn't get shown ) . The following code doesn't work.

 gridview.Rows[e.RowIndex].Cells[11].Visible = false;

Upvotes: 19

Views: 78752

Answers (6)

Ramgy Borja
Ramgy Borja

Reputation: 2458

if you want to hide gridview column, you should have a condition..

if(userlevel != 'Administrator')
{
      GridView.Columns["ColumnName"].Visible = false;
}

Upvotes: 0

GridView.Columns[index of Column].Visible = false;

Upvotes: -1

Robert Quinn
Robert Quinn

Reputation: 589

Call this how ever you see fit. The data is still available to the app whether visible or not.

private void showHideGridColumns(bool show)
{
    List<String> lstColNames = new List<string>();
    lstColNames.Add("Column1");
    lstColNames.Add("Column2");
    lstColNames.Add("Column3");
    lstColNames.Add("Column4");
    foreach (DataGridViewColumn Col in DataGridView1.Columns)
    {
        if (!lstColNames.Contains(Col.Name.ToString()))
        {
            Col.Visible = show;
        }
    }
}

Upvotes: 1

Leo Chapiro
Leo Chapiro

Reputation: 13979

Try this:

gridview.Columns["ColumnName"].Visible = false;

Hide Columns in the Windows Forms DataGridView Control

Upvotes: 56

Sohail Malik
Sohail Malik

Reputation: 335

This is 100% correct solution.... this.dataGridView1.Columns[0].Visible = false;

Upvotes: 6

Stuart
Stuart

Reputation: 1574

Add the column name/s to the DataKeyNames of the grid view...

<asp:gridview id="GridView1" runat="server" datakeynames="ColumnName" onselectedindexchange="GridView1_SelectedIndexChanged"></asp:gridview>

you can then access the datakeys in the code behind...

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    textbox.Text = GridView1.DataKeys[GridView1.SelectedIndex].Values["ColumnName"].ToString();
}

You can add more DataKeyNames by separating with a comma. Then you don't need to add the column to the GridView at all if you don't want to.

Upvotes: 0

Related Questions