Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I'm trying to hide a column in 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:

ASP.NET
<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)
            {
                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 5-Sep-14 2:04am
v3
Comments
kbrandwijk 4-Sep-14 19:46pm    
This is an ASP.NET question, please tag it as such to improve visibility of your question to the right audience.
[no name] 5-Sep-14 1:23am    
@kbrandwijk , ASP.NET tag is added with above question. Thanks

Without knowing which error you're actually getting, these things are wrong with the current code:

1. Your template column will appear to the left of the other columns, so compared to the Ordinal in your datasource, there is a +1 offset on all auto-generated columns
2. You should probably check the rowtype in your RowCreated event handler to see if it is a datarow or headerrow, because you will only have the cells in these rows:
C#
e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow


It would help however, to actually see the error message that you're getting. I never understand why people say there's an error message, don't include it in their post, and expect the right solution...
 
Share this answer
 
Comments
[no name] 5-Sep-14 1:40am    
@kbrandwijk, Above code that I pasted in this question runs perfectly if I define GridView1 in its most basic form i.e., <asp:GridView ID="GridView1" runat="server" OnRowCreated="GridView1_RowCreated">
But if I define GridView1 as I have pasted in the question, It is throwing "Specified argument was out of the range of valid values." error. Thanks
Hi,

make that cell invisible(i.e visible=false) in rowdatabound event
it is the best way.

ex:

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gr = e.Row;
if (e.Row.RowType == DataControlRowType.Header)
{
gr.Cells[i].Visible = false;
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
gr.Cells[i].Visible = false;
}
}


here i referes inidex of the cell.
 
Share this answer
 
Comments
[no name] 5-Sep-14 7:29am    
@chidura Thanks for your response but your proposed solution only works well with column indexes. What if I want to hide a column by its "name"?
chidura 9-Sep-14 1:15am    
use for loop for row in that event.. in that loop, use if condition to find the required column name.. once find then u can invisible that particular cell.

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