dynamic columns disappears after postback

可紊 提交于 2019-12-08 17:14:02

问题


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.


回答1:


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).




回答2:


I had been using:

EnableViewState="false"

in the GridView attributes. Removing it solved my problem!




回答3:


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



来源:https://stackoverflow.com/questions/7658049/dynamic-columns-disappears-after-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!