Reputation: 115
I have a GridView
with some BoundFields
and two TemplateFields
. In these two TemplateFields
, I dynamically create UserControls
containing a DropDownList
and a TextBox
, which users can modify.
When I try to get the values of the controls after a PostBack
, the values in BoundFields
are still there but my dynamic controls disappears. I can create them again but it won't get the user's values... How can I get these values before they're lost?
Here's some of my code:
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 button click event, I try to get the user control :
Case "String"
temp.ChampValeurApres = DirectCast(Tableau1.Rows(i).Cells(selectedColumn).Controls(1), TextBox).Text
but i get the error that it doesn't exist.
Upvotes: 10
Views: 6880
Reputation: 1
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 as well
Upvotes: 0
Reputation: 11
I had been using:
EnableViewState="false"
in the GridView
attributes. Removing it solved my problem!
Upvotes: 0
Reputation: 460380
You should create dynamic controls in RowCreated instead of RowDataBound because this event gets fired on every postback whereas RowDataBound
only will fire when the GridView
gets databound to it's DataSource
.
Dynamically created controls must be recreated on every postback with the same ID as before, then they retain their values in the ViewState and events will fire correctly(f.e. a DropDownList's SelectedIndexChanged
event).
So you should create them in RowCreated
and "fill" them in RowDataBound
(f.e. the DropDownList
datasource/Items or a TextBox
-Text).
Upvotes: 8