C# – How to hide column in GridView after DataBind

asp.netcdata-bindinggridview

I ask this question because I think I have different problem with this : How to hide gridview column after databind?

My gridview has data from database. I don't set any "td" in my code, but html changes the gridview to table and have "td". The problem is, I don't want the cell or "td" is shown on the page, I just want to receive the data in the cell to show the image in the database.

This is code to retrieve data from database:

   public static DataTable FetchAllImagesInfo(int id)
   {
     string sb = "Select img_content, Img_id, csrid FROM images WHERE Img_Id = " + id + ";";
     SqlConnection conn = DatabaseFactory.GetConnection();
     SqlDataAdapter da = new SqlDataAdapter(sb, conn);
     DataTable dt = new DataTable();
     da.Fill(dt);
     return dt;
    }

This is codebehind to bind GridView, here I tried to set Visible to true or false, but it doesn't work. I set column index manually because it's only has 3 column :

GridView1.DataSource = ProductAllLocationCatalog.FetchAllImagesInfo(_id);
GridView1.DataBind();
GridView1.Columns[0].Visible = true;
GridView1.Columns[1].Visible = false;
GridView1.Columns[2].Visible = false;

And, this is my aspx code :

<asp:GridView ID="GridView1" runat="server">
  <Columns>
    <asp:TemplateField runat="server">
       <ItemTemplate runat="server">
          <asp:Image ID="image1" runat="server" ImageUrl='<%#"Handler.ashx?csrid="+Eval("csrid") %>' style="max-height:400px; max-width:940px; text-align:center; margin:auto; display:block;" />
       </ItemTemplate>
     </asp:TemplateField>
  </Columns>
</asp:GridView>   

I just need the image from the database, not other. But if I only SELECT the image, gridview can not do DataBind(), and I can't get value of "csrid".

Thank you!

Best Answer

Try

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[1].Visible = false;
    e.Row.Cells[2].Visible = false;
}

I believe the issue is that your GridView is automatically generating your columns, and the GridView.Columns property only stores explicitly declared columns. Instead of hiding the column, you can hide the cells comprising the columns you don't want when each row is bound. It seems like there should be a better way to handle this, but outside of using explicitly declared columns, I don't know one.