How to hide columns of dynamically created gridview?


Dynamically created gridview columns can be hidden at gridview_RowCreated event.

GridView dataGridTemp = new GridView();
dataGridTemp.AutoGenerateColumns = true;
dataGridTemp.RowCreated += new GridViewRowEventHandler(dataGridTemp_RowCreated);
dataGridTemp.DataSource = ds;
dataGridTemp.DataBind();


gridview_RowCreated event

void dataGridTemp_RowCreated(object sender, GridViewRowEventArgs e)
{
    try
    {
        // Change header text if you want to change else remove these lines
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Text = "Column 1";
            e.Row.Cells[1].Text = "Column 2";
            e.Row.Cells[2].Text = "Column 3";
            e.Row.Cells[3].Text = "Column 4";
            e.Row.Cells[4].Text = "Column 5";
        }
        //Hide column
         e.Row.Cells[0].Visible = false;
    }
    catch (Exception ex)
    {
       //Error Message
    }
}