Click here to Skip to main content
15,302,857 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm trying to hide a column of a GridView. I've a template field in my GridView. Code that I'm applying to hide the desired column works well without having template field in the GridView. But because I need to have template field in my GridView, when I add it, code is giving error.

GridView (.aspx) code:

C#
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" AutoGenerateColumns="True" CellSpacing="4" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CellPadding="4" DataKeyNames="File_Name" GridLines="None" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" ForeColor="#333333" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnPageIndexChanging="GridView1_PageIndexChanging" AllowSorting="True" OnSorting="GridView1_Sorting" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnRowCreated="GridView1_RowCreated">
                        <PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="10" Position="Bottom" />
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:TemplateField HeaderText="File">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkbtnFileName" runat="server" CommandArgument='<%# Eval("File_Name") %>' CommandName="Download" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                    </asp:GridView>


.cs code for PageLoad() event is:

C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //BindGrid();
                SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        String sql = "select * from dbo.Documents";
                        cmd.Connection = con;
                        cmd.CommandText = sql;
                        con.Open();
                        DataSet ds = new DataSet();
                        using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
                        {
                            adp.Fill(ds);
                        }
                        DataTable mytable = ds.Tables[0];
                        GridView1.DataSource = mytable;
                        GridView1.DataBind();
                        MultiView1.SetActiveView(vHome);
                        btnBacktoHome.Visible = false;
                        lblStatus.Visible = false;
                    }
                }
            }
        }

RowCreated() event code is:

C#
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    DataTable myGridDataTable = null;
    TableCell tblcell1;
    myGridDataTable = (DataTable)((GridView)sender).DataSource;
    if (myGridDataTable != null)
    {
        tblcell1 = e.Row.Cells[myGridDataTable.Columns["DocumentsID"].Ordinal];
        tblcell1.Visible = false;
    }

}


Above code runs and brings desired results if I remove <TemplateField> from <GridView1> .aspx code. Can anyone tell me why number of enumerated cells in `e.Row.Cells` in GridView1_RowCreated() event is 1 when myGridDataTable is filled with datatable having 25 columns. ? Thanks in advance.
Posted
Updated 4-Sep-14 9:56am
v4
Comments
kbrandwijk 4-Sep-14 19:54pm
   
Always nice to see a repost, with a solution, just after answering your original question... Too bad users don't get bans for reposting on this site.
[no name] 5-Sep-14 13:01pm
   
You've to do it to get your question up on the questions stack. Thank you.

Pretty sure you want the rowdatabound event and not the Rowcreated event. Thats why your grid doesn't know about the 25 fields in your datatable. Data hasn't been bound to the grid yet on the rowcreated event.

Once you change this to the Gridview1_RowDataBound event. Add this line inside

e.Row.Cells[index].Visible = false;

where index is the column you want to hide.
   
Comments
[no name] 6-Sep-14 5:35am
   
@j snooze `e.Row.Cells[index].Visible=false;` hides column by `index`. I want to hide it by `Column Name`. Thanks
C#
protected void gridview_DataBound(object sender, EventArgs e)
{
    if(cat_check.SelectedItem != null)
    {
        string columnName =  SelectedItem.Text;
        var column = gridView1.Columns.Cast<datacontrolfield>()
            .FirstOrDefault(c => c.HeaderText == columnName);
        if (column != null) column.Visible = false;
    }
}
</datacontrolfield>
   
Comments
[no name] 5-Sep-14 13:00pm
   
what is SelectedItem? @Gihan Liyanage where do you see a "SelectedItem" in my code? ha ha ha

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900