(动态控件),但无法找到控件在页面Pre_Init我可以使用下面的代码获取控件的名称,但它无法在面板中找到控件,即使它存在。那为什么呢?我需要做的是在回收控制处理之前获取它的价值。虽然存在Asp.Net
注意:这只是一个示例。
下面是HTML
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm2.aspx.vb" Inherits="DynamicControls_GetControlUnloaded.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="width: 200px;">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
这里是后面的代码
Public Class WebForm2
Inherits System.Web.UI.Page
Dim current_val As Object
Private Sub WebForm2_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
Dim postback_control As Control = GetPostBackControl(Me.Page)
If postback_control IsNot Nothing Then
Select Case postback_control.GetType
Case GetType(DropDownList)
current_val = CType(postback_control, DropDownList).Text
Case GetType(TextBox)
current_val = CType(postback_control, TextBox).Text
Case GetType(CheckBox)
current_val = CType(postback_control, CheckBox).Checked
Case GetType(RadioButton)
current_val = CType(postback_control, RadioButton).Checked
End Select
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Create Dynamic controls
Call BuildControls()
End Sub
Private Sub BuildControls()
For i As Integer = 0 To 2
Dim ddl As New DropDownList
ddl.Items.Add("Item 1")
ddl.Items.Add("Item 2")
ddl.Items.Add("Item 3")
ddl.Style.Add("margin", "3px")
ddl.ID = "Ctrl" & i.ToString
ddl.AutoPostBack = True
ddl.Width = 150
PlaceHolder1.Controls.Add(ddl)
Next
End Sub
Public Shared Function GetPostBackControl(ByVal thePage As Page) As Control
Dim myControl As Control = Nothing
Dim ctrlName As String = thePage.Request.Params.Get("__EVENTTARGET")
If ((ctrlName IsNot Nothing) And (ctrlName <> String.Empty)) Then
myControl = thePage.FindControl(ctrlName)
Else
For Each Item As String In thePage.Request.Form
Dim c As Control = thePage.FindControl(Item)
If (TypeOf (c) Is System.Web.UI.WebControls.Button) Then
myControl = c
End If
Next
End If
Return myControl
End Function
End Class
你为什么要这样做而不是正常的方式呢? – ivowiblo
@ivowiblo这个项目是动态的。我试图在重新创建之前获取控件的值(dropdownlist)。 – TroyS
哦,我看到你改变了整个例子,让我现在检查:) – ivowiblo