asp.net – 动态创建的DropDownList在Postback上丢失了ListItems

前端之家收集整理的这篇文章主要介绍了asp.net – 动态创建的DropDownList在Postback上丢失了ListItems前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个页面,其中包含一些动态创建的控件(TextBox和DropDownList).发生回发时,TextBox会保留其值,但DropDownLists会丢失其ListItem.
这非常令人困惑,因为页面级DropDownList也保留其ListItems.任何人都可以看到下面的代码有什么问题吗?

任何帮助解决这个问题将不胜感激.

<%@ Page Language="VB"%>

<script runat="server">
  Protected Sub Page_Init(ByVal sender As Object,ByVal e As System.EventArgs)
    If Not Page.IsPostBack Then
      ddlFixed.Items.Add(New ListItem("12","13"))
      ddlFixed.Items.Add(New ListItem("14","15"))
    End If
    Dim i As Integer
    For i = 0 To 3
      Dim ddl As New DropDownList
      ddl.ID = "ddlPage" & i
      ddl.EnableViewState = True
      If Not Page.IsPostBack Then
        ddl.Items.Add(New ListItem("12","13"))
        ddl.Items.Add(New ListItem("14","15"))
      End If
      pnlDynamic.Controls.Add(ddl)
      Dim txtBx As New TextBox
      txtBx.ID = "txtPage" & i
      If Not Page.IsPostBack Then
        txtBx.Text = "Preset"
      End If
      pnlDynamic.Controls.Add(txtBx)
    Next
  End Sub
</script>


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server" enableviewstate="true">
  <div>
    <br />
    <br />
    <a href="Default.aspx">Get-Request</a>
    <br />
    <br />
    <asp:Panel runat="server" ID="pnlDynamic" EnableViewState="true" />    
    <br />
    <br />
    <asp:DropDownList runat="server" ID="ddlFixed" />
    <asp:Button runat="server" ID="btn" Text="Postback"/>
  </div>
  </form>
</body>
</html>

解决方法

我找到了一个解决方案,可以让我在回发中保持视图状态.
它是调用ItemCollection的TrackViewState.
CType(ddl.Items,IStateManager).TrackViewState()

感谢大家的帮助.

这是工作解决方案:

<%@ Page Language="VB"%>

<script runat="server">
  Protected Sub Page_Init(ByVal sender As Object,"15"))
    End If
    Dim i As Integer
    For i = 0 To 3
      Dim ddl As New DropDownList
      ddl.ID = "ddlPage" & i
      CType(ddl.Items,IStateManager).TrackViewState()
      If Not Page.IsPostBack Then
        ddl.Items.Add(New ListItem("12","15"))
      End If
      pnlDynamic.Controls.Add(ddl)
      Dim txtBx As New TextBox
      txtBx.ID = "txtPage" & i
      If Not Page.IsPostBack Then
        txtBx.Text = "Preset"
      End If
      pnlDynamic.Controls.Add(txtBx)
    Next
  End Sub
</script>


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server" >
  <div>
    <br />
    <br />
    <a href="Default.aspx">Get-Request</a>
    <br />
    <br />
    <asp:Panel runat="server" ID="pnlDynamic" />    
    <br />
    <br />
    <asp:DropDownList runat="server" ID="ddlFixed" />
    <asp:Button runat="server" ID="btn" Text="Postback"/>
  </div>
  </form>
</body>
</html>
原文链接:https://www.f2er.com/aspnet/247282.html

猜你在找的asp.Net相关文章