Keeping DataGrid Columns through Postback

A

Allen K

I have a Datagrid that has programmatically added columns, as well as
columns added through the VS.NET DataGrid Control Editor. Everything is
fine the first time around when the page loads, but when I do a postback,
the columns that I programmatically added disappear. The columns I added
through the Control Editor however are still visible.

Anyone have any idea as to what the problem might be? Does it have
something to do with the columns not persisting in viewstate? How do I fix
this?

Thanks!
Allen
 
T

Teemu Keiski

Hi,

you need to add columns on every request, they act like other controls in
that sense that they need to be recreated for each request.
 
A

Allen K

I tried re-adding the columns in the Page_Load method on every postback but
that doesn't seem to work.. The only way I can get it to work is if I
rebind the DataGrid each time.. however that doesn't seem like an elegant
solution considering that I have a huge datagrid and the same information
needs to be persisted through 10 or so postbacks.. I don't want to have to
rebind each time..

Help please!
 
G

Guest

I am doing the exact same thing you are requesting. Here
is what you do:
1. You must wire-up a method to the eventhandler of the
grid called ItemDataBound.
this.dgServices.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler
(this.dgServices_ItemDataBound);
2. Then create a method, usually the same name as the
control with the event after the underscore.
private void dgServices_ItemDataBound(object sender,
DataGridItemEventArgs e)
3. Then, depending on what you are displaying (Header,
Item, Footer) you must write those out to the control.
if(e.Item.ItemType == ListItemType.Header)
if(e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
if(e.Item.ItemType == ListItemType.Pager)

That should get you started. Have fun!

Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top