Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView Hide Column by code

Tags:

c#

asp.net

I want to hide ID column in my GridView, I knew the code

GridView1.Columns[0].Visible = false; 

but the surprise was that my count property for my GridView columns is 0 !!! while I can see data in the GridView, so any ideas?

Thank you,

Update:

here is the complete code for the method which populate the GridView

public DataSet GetAllPatients() {     SqlConnection connection = new SqlConnection(this.ConnectionString);      String sql = "SELECT [ID],[Name],[Age],[Phone],[MedicalHistory],[Medication],[Diagnoses] FROM [dbo].[AwadyClinc_PatientTbl]order by ID desc";      SqlCommand command = new SqlCommand(sql, connection);      SqlDataAdapter da = new SqlDataAdapter(command);      DataSet ds = new DataSet();      da.Fill(ds);      return ds;  } 
like image 412
amr osama Avatar asked Sep 29 '10 06:09

amr osama


People also ask

How do I hide a column in grid view?

To hide a column programmaticallySet the DataGridViewColumn. Visible property to false .

How to hide particular column in GridView in c#?

The way to hide a column in a DataBound GridView is to trap the RowCreated Event and set a Cell inside the column of the row to Visible = false.

How do you hide ASP BoundField?

You can do it by two ways. By hidden field it will easy to maintain to get value by name of hidden field instead of finding cell value in code. 1) Remove the BoundField of ID and add Hidenfield with value as Id which will use for File id on RowDataBound. So change in HTML and Code like below.

What is GridView RowDataBound event in asp net?

The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.


2 Answers

GridView.Columns.Count will always be 0 when your GridView has its AutoGenerateColumns property set to true (default is true).

You can explicitly declare your columns and set the AutoGenerateColumns property to false, or you can use this in your codebehind:

GridView.Rows[0].Cells.Count

to get the column count once your GridView data has been bound, or this:

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

to set a column invisible using your GridView's RowDataBound event.

like image 126
Brissles Avatar answered Sep 21 '22 15:09

Brissles


This helped for me

this.myGridview.Columns[0].Visible = false; 

Here 0 is the column index i want to hide.

like image 26
user2508258 Avatar answered Sep 23 '22 15:09

user2508258