Remove dynamicly columns from an gridview

Im making an c# class library project with an dataset and an gridview. Everything works fine. The gridview shows some information. But I would like to remove or disable some columns from the gridview. It is simple in the designer, but I don't know how it works for an class library project(in runtime code). Here is the code I have:

 gvBoodschapper.DataSource = statsTableAdapter.GetUsersToday().DefaultView;
 gvBoodschapper.DataBind();

 I try something like this, but it doesnt work and gives me errors:

gvBoodschapper.DataSource = statsTableAdapter.GetUsersToday().DefaultView;
gvBoodschapper.Columns.RemoveAt(2);
gvBoodschapper.DataBind(); 


Who can help me please?

 

0
khalidelmeknesi
4/1/2009 1:39:26 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

12 Replies
658 Views

Similar Articles

[PageSpeed] 0

try to removeit after the DtaBind()

 

gvBoodschapper.DataSource = statsTableAdapter.GetUsersToday().DefaultView;

gvBoodschapper.DataBind();  


gvBoodschapper.Columns.RemoveAt(2);


Please mark as answer if it helped u!
0
kavita_khandhadia
4/1/2009 1:55:52 PM

Before Setting the GridView DataSource remove the columns and then set it as datasource.

DataTable dt = statsTableAdapter.GetUsersToday();

dt.Columns.RemoveAt(2);

gvBoodschapper.DataSource = dt;
gvBoodschapper.DataBind();

Let us know if you got what you wanted.

 


Avi
0
vemulapalli26
4/1/2009 1:58:56 PM

If the AutoGenerateColumns is set to true for your GridView, there is no way that you can manipulate the columns in the GridView directly except that you can manipulate the interior cells. Use this in the RowDataBound event....

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells.RemoveAt(2);  
}

If your GridView has AutoGenerateColumns is set to false, then your code should work.

When the AutoGenerateColumns property is set to true, an AutoGeneratedField object is automatically created for each field in the data source. Each field is then displayed as a column in the GridView control in the order that the fields appear in the data source. This option provides a convenient way to display every field in the data source; however, you have limited control of how an automatically generated column field is displayed or behaves.

Automatically generated bound column fields are not added to the Columns collection. Instead of letting the GridView control automatically generate the column fields, you can manually define the column fields by setting the AutoGenerateColumns property to false and then creating a custom Columns collection. In addition to bound column fields, you can also display a button column field, a check box column field, a command field, a hyperlink column field, an image field, or a column field based on your own custom-defined template

Hope this helps. Mark as Answer if it does.

 


KAMMIE
Don't forget to Mark as Answer on the post that helped you. It encourages them to share their knowledge, and it helps others to easily identify the solution.
0
kammie
4/1/2009 2:24:05 PM

 Thx everybody,

The answer of vemulapalli26 works, but I can't remove index 0 because that is the id(primary key). How can I change the visible property of column 0 ??

0
khalidelmeknesi
4/1/2009 2:52:02 PM

Use this....

GridView1.Columns[0].Visible = false;

Hope it helps.


KAMMIE
Don't forget to Mark as Answer on the post that helped you. It encourages them to share their knowledge, and it helps others to easily identify the solution.
0
kammie
4/1/2009 3:17:04 PM

 I have try this:

            DataTable dt = statsTableAdapter.GetUsersToday();
            gvBoodschapper.Columns[0].Visible = false;
            gvBoodschapper.DataSource = dt;
            gvBoodschapper.DataBind();

It gives me this error:

Index was out of range. Must be non-negative and less than the size of the collection.<br>Parameter name: index body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }

Server Error in '/' Application.

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
   System.Collections.ArrayList.get_Item(Int32 index) +7483656
   System.Web.UI.StateManagedCollection.System.Collections.IList.get_Item(Int32 index) +12
   System.Web.UI.WebControls.DataControlFieldCollection.get_Item(Int32 index) +8
   LunchRegistratieFront.LunchRegistratie.Render(HtmlTextWriter writer) +382
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   Microsoft.SharePoint.WebPartPages.SPChrome.RenderPartContents(HtmlTextWriter output, WebPart part) +66

[WebPartException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
   Microsoft.SharePoint.WebPartPages.SPChrome.RenderPartContents(HtmlTextWriter output, WebPart part) +140
   Microsoft.SharePoint.WebPartPages.SPChrome.RenderWebPart(HtmlTextWriter output, WebPart part) +63
   Microsoft.SharePoint.WebPartPages.WebPartZone.RenderZoneCell(HtmlTextWriter output, Boolean bMoreParts, WebPart part) +144
   Microsoft.SharePoint.WebPartPages.WebPartZone.RenderWebParts(HtmlTextWriter output, ArrayList webParts) +495
   Microsoft.SharePoint.WebPartPages.WebPartZone.Render(HtmlTextWriter output) +902
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +163
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +51
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
   System.Web.UI.Page.Render(HtmlTextWriter writer) +29
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 

Whats the problem??

0
khalidelmeknesi
4/8/2009 1:36:09 PM

You might be trying to access the columns which were removed. Check out if thats the case.


Avi
0
vemulapalli26
4/8/2009 1:47:15 PM

No thats not the case..I only wil set the visible property to false like this code:

            DataTable dt = statsTableAdapter.GetUsersToday();
            gvBoodschapper.Columns[0].Visible = false;
            gvBoodschapper.DataSource = dt;
            gvBoodschapper.DataBind();

 When I run this code it wil result 0:

  String countColumns = gvBoodschapper.Columns.Count.ToString();

Someone know why?

 

0
khalidelmeknesi
4/9/2009 7:04:36 AM
Do you have any columns set in the GridView in the aspx page? If not, then you cannot access that property. Columns created automatically by the DataSource cannot be accessed through GridView. Refer the explanation in my first post in this thread. Hope it helps.
KAMMIE
Don't forget to Mark as Answer on the post that helped you. It encourages them to share their knowledge, and it helps others to easily identify the solution.
0
kammie
4/9/2009 11:19:48 AM

 I don't have an aspx page. It is an class library project. But when I run the webpart it shows some rows with some colums.

0
khalidelmeknesi
4/9/2009 11:35:10 AM

Try setting the visible= false statement after the DataBind. I think you are trying to hide the columns in gridview before binding the columns to gridview. Can't really say if this solves the problem.


Avi
0
vemulapalli26
4/9/2009 6:05:49 PM

I have try this, but it gives the same error:

DataTable dt = statsTableAdapter.GetUsersToday();

            dt.Columns.RemoveAt(1);
            dt.Columns.RemoveAt(1);
            dt.Columns.RemoveAt(1);
            dt.Columns.RemoveAt(1);
            dt.Columns.RemoveAt(1);
            
            gvBoodschapper.DataSource = dt;
            gvBoodschapper.HeaderStyle.BackColor = Color.Blue;
            gvBoodschapper.DataBind();

            gvBoodschapper.Columns[1].Visible = false;

 

Is there some other solution?

0
khalidelmeknesi
4/17/2009 12:51:09 PM
Reply:

Similar Artilces:

remove a gridview column dynamically, removes controls in template columns
I have a interface with a treeview and a gridview. The gridview has two templatefields that handles insert/update/deletes. The gridview is handling editing of different tables so I create the other columns in the gridview dynamically as boundfields. The user selects the table to edit in the treeview. The problem I am having happens when the user selects a table to edit the second time. The code that executes removes all bound fields, (dynamically added when user selected the first table in the treeview), but not the two template fields, and then adds boundfields specifi...

Dynamic Slave Controls
I am working a solution to enhance slave controls. I have created a proof of concept based on the 2.04 code base that shows how to load slave controls without switching to the admin view. I have included a sample module that contains 3 view controls. Each control has a row of buttons that can be used to load one of the other 2 controls. (and no I am not using panels.) The default control has a drop down of other instances of the dynamic control that exist on the current tab. Using the module communicator you can raise an event from one control that tells another instance of the module what c...

GridView Dynamic Column, Controls
Hello I have a data grid, i define its edittemplete , itemtemplete in .cs file because i need things dynamic, i dont want any Select , Edit , Update Button on Grid,i made my grid click able, when i click on row , its show row in edit  version fine yet, but when i click ne other row its dont make changed in last row ? how could i bind it ? do we must need to put updated button? plz help uswe need to giv look of desktop grid?let me know if you have any query?  Umer KhanSr. Software EngineerUmer.Khan@systemsltd.com------------------------Click "Mark As Answer" iff,It he...

Creating Dynamic Controls in Gridview Columns
I need a gridview that needs to show information about a product and show information about this product. In the gridview I also want to run a count of how many products there are. To do this I have used an sqldatasource to bind the select information that is about the product and then in the Gridview Databound event i use another sqldatasource to query the Count for each product and then attach to the last column. This all works fine and gets me the results. idont know if it is effecient but it works. I now want the count column to be c...

Dynamic Gridview with dynamic controls
Hi, I’m trying to insert some dynamic linkbutton inside the rows of a gridview. 1. I First generate the columns inside a datatable. //Create an instance of DataTable DataTable dt = new DataTable(); DataColumn dcol = new DataColumn(”Measure”, typeof(System.String)); dt.Columns.Add(dcol); for (int i = 1; i < 5; i++) { //Create an ID column for adding to the Datatable dcol = new DataColumn(i.ToString(), typeof(LinkButton)); dt.Columns.Add(dcol); } 2.then, I created a row and add it to the datata...

Dynamically create controls in GridView template column
Hi,this is my first post so please be nice :)I have a situation where I'm loading GridView from XML data source and I need to dynamically create a TABLE control inside grids template column.One of table's columns has an editable TextBox, so there could be unknown number of rows in a gridview and unknown number of rows in each table.At the moment I'm creating those tables inside  GridView_RowDataBound event and all works fine.Problem is that when user clicks in "Update" button table controls are gone because they are dynamically created.My question is how can I crea...

Gridview control removing consecutive spaces in column output
 Hi, i am using a simple GridView to retrieve data from a SQL view, and if there are consecutive spaces in the string in a particular column, something (asp?) is removing the 2nd space, and then the output has only 1 space, which is incorrect for this string. Interestingly, if I retrieve the same column with a specific select statement in a code behind file, and then output it via either response.write, or in a text box, it does the same thing.   I have debugged while doing this and in the Autos window, the string is correct (with two consecutive spaces), then when it is ...

Gridview: Dynamic Textbox in dynamic column
Hi,I have created a spreadsheet like gridview which have some dynamic columns.and I have add the textboxes to the cell during RowDataBound, however, when I do submit, there are no controls in the cell!'--------------------------------------------------------------------------------Code to add textbox:txtbox = New TextBoxtxtbox.Width = New Unit(m_cellwidth, UnitType.Pixel)txtbox.Attributes.Add("id", stmpID)e.Row.Cells(j).Controls.Add(txtbox)'--------------------------------------------------------------------------------Code to get text from textbox (but doesn't work):va...

How to implement dynamic controls in dynamic gridview
 I have to view three controls(dropdownlist,textbox,checkbox) in an gridview row and if I select dropdonlist or checkbox  the next row with same controls will have to display.Will you help me to do this Hi sreenatht:            I am sorry that I can't quite understand what you mean. "How to implement dynamic controls in dynamic gridview"?? What effect do you want? Further, sreenatht:the next row with same controls will have to display You don't want it to display? Don't display what? Or hide.   &...

how to open new window when click on the dynamic column in gridview control
Hi I am working with Gridview Control with c#.net.from database i am loading 10 columns dynamically on the gridview control.i have to open new widow through javascript when i click on the 8th column.how can i write on click event for the dynamic column in gridview control.your help appreciatable. Thanks in advance        shiva Do you have a hyperlink or button in the 8th column?  And should this happen on each row or the header? Rob Millswww.dotnetadvisor.com...

trouble creating a reusable GridView with dynamic Template command Columns VB.NET
I've created a single GridView control that I want to reuse.  My goal is to bind the initial dataset with a programmatically created command column, pass the arguments to a universal RowCommand event handler and dynamically change the DataSource, commandArgument, commandName, and Databind again. I haven't had any success in implementing this idea.  I've tried creating separate template class and Import it, but then I'm unable to assign the properties to the Command column. I just need someone to point me in the right direction.  I've found hundred...

Gridview and dynamically created controls
Hello, I have a gridview with a lot of rows. This means I can't create the the correct controls (like dropdowns) at once but I have to create them once the user wants to edit a row. Anyhow, this is an example of how I create a dropdown:  Dim lstPersCat As New DropDownList lstPersCat.ID = "lstPersCat" Dim strUserGroups(10) As String strUserGroups = retUserGroups(CType(gvResults.Rows(e.NewEditIndex).Cells(9).Controls(0), TextBox).Text.ToString) For i As Integer = 0 To strUserGroups.Length - 1 If Len(strUserGroups(...

Binding GridView Columns with controls outside the GridView
HiI already posted this issue but couldn't get the proper resolution so making it more clear;Problem is my controls are outside the grid. Like ive text boxes, for First Name and Last Name and dropdown for country. User can fill these fields for entering a new record and also update the existing by selecting it from the grid.Like user selects a row from the grid and its contents will be displayed on the textboxes and drop downs that are out side the grid.Hope i could explain it better now.  RegardsMohsin Shahzad You could use a DetailsView or FormView control that is linked to...

How to control the position of Gridview when Gridview is dynamically binding
Hello:  I have one Gridview on the left side. Each field has the hyperlink. When uses click the link, I need to pass this string to another dynamic Gridview control. This Gridview control is needed to dynamically bind. This Gridview control is need to be stay on the right side of the first Gridview.  Here is my dynamic binding Gridview code: TableRow row = new TableRow();tbl.Rows.Add(row);        ……….. GridView gv1 = new GridView();       ……cel1.Controls.Add(gv1); Here is my questions. How I could p...

Web resources about - Remove dynamicly columns from an gridview - asp.net.presentation-controls

LoL Library, League of Legends Guide & Database for iPhone, iPad, and iPod touch on the iTunes App Store ...
Get LoL Library, League of Legends Guide & Database on the App Store. See screenshots and ratings, and read customer reviews.

Sony joins indies at Amie Street—without dynamic pricing
Amie Street is known for its indie music collection, the ease of music …

Posts tagged Alien swarm at Big Download Blog
It's hard to complain about a game that's completely free to download and play online but there have apparently been those folks who want more ...

Rc/Funge-98
Welcome to the official home for the Rc/Funge-98 Funge interpreter. Rc/Funge-98 was one of the first Funge interpreters to implement the Funge-98 ...

Legend of Dungeon
... + final relase + the two planned expansions! + Steam keys coming soon!) buy the soundtrack on: Amazon iTunes Rapsody The music in is dynamicly ...

First hands-on with the Kin One and Kin Two - TIME.com
Microsoft’s acquisition of Danger in February of 2008 renewed interest in the languishing mobile operating system formerly known as Windows Mobile. ...

Credits for the TerminatorFiles sites and services
Credits are due to those that helped make TerminatorFiles what it is today. A detailed Terminator fanportal cranked with Terminator movie info, ...

Anonymous Hamburg: English
For most of us there is only one Internet. The World Wide Web. We have learned but won't accept, that it is watched, monitored, filtered, depriorized ...

mediola® - Investor Relations
Our investors page provides you with a quick overview of the most important information about our company.


Resources last updated: 1/15/2016 9:18:56 AM