gpt4 book ai didi

asp.net - 动态创建的 DropDownList 在回发时丢失 ListItems

转载 作者:行者123 更新时间:2023-12-02 10:27:29 33 4
gpt4 key购买 nike

我有一个页面,其中包含一些动态创建的控件(TextBox 和 DropDownList)。发生回发时,TextBox 保留其值,但 DropDownList 会丢失其 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>

最佳答案

我找到了允许我在回发期间保持 View 状态的解决方案。就是调用ItemCollection的TrackViewState。

CType(ddl.Items, IStateManager).TrackViewState()

感谢大家的帮助。

这是可行的解决方案:

<%@ 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
CType(ddl.Items, IStateManager).TrackViewState()
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 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>

关于asp.net - 动态创建的 DropDownList 在回发时丢失 ListItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/623611/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com