Dynamic columns disappear after postback

I have a GridView with some BoundFields and two TemplateFields . In these two TemplateFields I dynamically create a UserControls containing a DropDownList and a TextBox that users can modify.

When I try to get control values ​​after PostBack , the values ​​in BoundFields still exist, but my dynamic controls disappear. I can create them again, but it won’t get user values ​​... How can I get these values ​​before they are lost?

Here are some of my codes:

In the RowDataBound event:

 Select Case type Case "BooleanBis" e.Row.Cells(2).Controls.Clear() Dim list1 As BooleanBisList = New BooleanBisList(avant, False) e.Row.Cells(2).Controls.Add(list1) e.Row.Cells(4).Controls.Clear() Dim list2 As BooleanBisList = New BooleanBisList(apres, True) e.Row.Cells(4).Controls.Add(list2) Case "Boolean" e.Row.Cells(2).Controls.Clear() Dim list3 As BooleanList = New BooleanList(avant, False) e.Row.Cells(2).Controls.Add(list3) e.Row.Cells(4).Controls.Clear() Dim list4 As BooleanList = New BooleanList(apres, True) e.Row.Cells(4).Controls.Add(list4) End Select 

In my click button event, I am trying to get user control:

 Case "String" temp.ChampValeurApres = DirectCast(Tableau1.Rows(i).Cells(selectedColumn).Controls(1), TextBox).Text 

but I get an error that it does not exist.

+8
controls gridview postback
source share
3 answers

You should create RowCreated dynamic controls instead of RowDataBound , because this event will be fired on every postback, while RowDataBound will only fire when the GridView receives a DataSource binding to it.

Dynamically created controls should be recreated at each postback with the same identifier as before, then save their values ​​in the ViewState , and the events will fire correctly (fe DropDownList SelectedIndexChanged ).

So, you have to create them in RowCreated and "fill" them in RowDataBound (fe DropDownList datasource / Items or TextBox -Text).

+8
source share

I used:

 EnableViewState="false" 

in the attributes of the GridView . Removing this problem solved my problem!

0
source share

i just did

 protected void Page_Load(object sender, EventArgs e) { if (!(Page.IsPostBack)) { // Put the selected items which u want to keep on postback } else { //regenerate auto created controls } } 

and it worked

0
source share

All Articles