Click here to Skip to main content
15,924,402 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
string qry = "select * from Users where UserName='Admin'";
       da = new SqlDataAdapter(qry, connection);
       DataSet ds = new DataSet();
       da.Fill(ds);
       GridView1.DataSource = ds.Tables[0];
       GridView1.DataBind();


       GridView1.Columns[0].Visible = false;
      // GridView1.Columns[1].Visible = false;// error//


Now to hide 1st column (Columns[0]) it works but when I want to Hide column 2nd (Columns[1]) it is showing error that :

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

While i have 5 column in my Table


Thanks in Advance.......
Posted
Updated 2-Jan-12 3:51am
v2

First, don't select everything from a table (*). Just the columns you need. While this is going to perform better, it also is going to work better when new columns are added to your table.

About the column hiding. I'd prefer not to let the gridview to populate the columns. Instead create the columns by hand (in code) and bind the datatable to the gridview after that.
 
Share this answer
 
Comments
Pr!y@ 3-Jan-12 6:56am    
Thanks Mika Wendelius
Wendelius 3-Jan-12 8:45am    
You're welcome :)
If it is giving you an "Index out of range" error, then there must be less than 2 columns in the collection.
If you are sure that your table contains 5 columns, then the SELECT query must be returning no rows, or your table has not got any columns yet. Check it: put some tracing stuff in or add a breakpoint and look at the collection itself.
 
Share this answer
 
Comments
Pr!y@ 2-Jan-12 10:15am    
If I am not using :::

GridView1.Columns[0].Visible = false;
GridView1.Columns[1].Visible = false;

Then Grid View is Showing all 5 Column

I have added a Hyper Link Also With Hyper Link Total Column are 6.
OriginalGriff 2-Jan-12 10:19am    
Yes - but it may depend on where you do it. Have you tried looking at the collection when the error occurs?
you can hide columns at design time.

if your application needs only 4 columns then write only 4 column name in select query.
 
Share this answer
 

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