如何:在ASP.NET中使用动态控件

介绍

有时,在开发Web应用程序时,我们需要能够根据用户选择动态加载控件。 本文介绍了一个简单的场景,其中需要根据用户输入动态加载TextBox控件。 可以进一步扩展此简单示例,以动态加载自定义Web用户控件。

背景

请熟悉一下

ASP.NET页面生命周期 。 至关重要的是,要理解这一周期以避免混乱的问题。 场景

为用户提供一个DropDownList,以便让他们选择要显示的TextBox的数量。 检索用户输入的值并将其显示在句子中。

动态解决方案

首先,我们需要为TextBoxes分配足够的空间。

对于此示例,我将使用文本框数组,在您的项目中,您可以根据需要从数据库等动态创建任意数量的控件。

(C#)


private TextBox textBoxArr(5)  
(VB.NET)

Private textBoxArr(4) As TextBox 
现在,我们声明了一个由5个TextBox组成的数组,但是在使用这些TextBox之前,我们必须实例化它们(创建它们的实例)。 我们在Page_Init方法中执行此操作。

之所以在Page_Init方法中执行此操作,是因为此方法在ASP.NET加载页面的ViewState之前发生。 记得ViewState包含页面的所有Objects属性。 ASP.NET会在Page_Init方法执行完成后立即设置对象的属性。 如果您此时尚未实例化TextBox(控件),则它们将不包含任何属性(包括我们感兴趣的Text属性)。

(C#)


private void Page_Init(Objectsender, System.EventArgs e) 
{
    //This event happens before any controls are initialized by ASP.NET
    //The ViewState for objects has not been loaded.
    //After this event happens, the ViewState is loaded for each control and the object's properties are filled with the values submitted. 
    //Creating the TextBox Objects that are dynamically shown in the web page
    //according to the number selected from a DropDownList
        for(int i = 0; i < textBoxArr.Length - 1; i++)
        {   textBoxArr(x) = New TextBox();
            textBoxArr(x).ID = "myTextBox" + x.ToString();
            textBoxArr(x).Visible = False; //Initializing the TextBox so that it is not rendered in the browser 
            Pnl_TextBoxes.Controls.Add(textBoxArr(x)); //Adding the TextBox to the Panel that holds the text boxes.
        } 
} 
(VB.NET)

Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    'This event happens before any controls are initialized by ASP.NET'
    'The ViewState for objects has not been loaded.'
    'After this event happens, the ViewState is loaded for each control and the object's properties are filled with the values submitted.' 
    'Creating the TextBox Objects that are dynamically shown in the web page'
    'according to the number selected from a DropDownList'
        For x As Integer = 0 To textBoxArr.Length - 1
            textBoxArr(x) = New TextBox
            textBoxArr(x).ID = "myTextBox" + x.ToString
            textBoxArr(x).Visible = False 'Initializing the TextBox so that it is not rendered in the browser 
            Pnl_TextBoxes.Controls.Add(textBoxArr(x)) 'Adding the TextBox to the Panel that holds the text boxes.
        Next 
End Sub 
请记住,必须将动态创建的控件添加到页面才能显示和使用它们。 在此示例中,我们将控件添加到已经属于页面一部分的面板中。

因此,现在用户可以选择使用最多6个文本框,并且我们可以检索用户已在这些文本框中输入的Text值。

下面的代码显示用户从名为“ numTextBoxes”的DropDownList中选择的TextBox的数量:

(C#)


private numTextBoxes_SelectedIndexChanged(System.Objectsender, System.EventArgs e) 
{
        For(int i= 0; i < numTextBoxes.SelectedValue - 1; i++)
        {
            textBoxArr(x).Visible = True //Setting the TextBox visible property to True
        }
} 
(VB.NET)

Protected Sub numTextBoxes_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles numTextBoxes.SelectedIndexChanged
        For x As Integer = 0 To numTextBoxes.SelectedValue - 1
            textBoxArr(x).Visible = True 'Setting the TextBox Visible property to True'
        Next
End Sub 
以下代码是如何从动态创建的TextBox中检索文本值的示例。 本示例中的方法在名为lbl_message的标签中显示从TextBoxes检索到的文本。

(C#)


private void btnText_Click(Object sender, System.EventArgs e) 
{
        StringBuilder str = New System.Text.StringBuilder(); 
        for(int i = 0;i < textBoxArr.Length - 1)
        {
            If (textBoxArr(i)!= null)
            {
                str.Append(" " + textBoxArr(i).Text); //Grabbing the text from the TextBox...remember that at this stage the TextBox's Text property has already been set by ASP.NET according to its ViewState
            }
        } 
        //Showing in a label what was in the TextBoxes
        lbl_message.Text = "message: " + str.ToString();
    } 
(VB.NET)

Private Sub btnText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnText.Click 
        Dim str As New StringBuilder 
        For i As Integer = 0 To textBoxArr.Length - 1
            If textBoxArr(i) IsNot Nothing Then
                str.Append(" " + textBoxArr(i).Text) 'Grabbing the text from the TextBox...remember that at this stage the TextBox's Text property has already been set by ASP.NET according to its ViewState
            End If
        Next 
    'Showing in a label what was in the TextBoxes
        lbl_message.Text = "message: " + str.ToString
     End Sub 
使用自定义Web用户控件的动态解决方案

将Web用户控件动态加载到页面中时,必须在该页面中注册该控件。 为此,ASP.NET为我们提供了Page.LoadControl()方法。

使用自定义Web用户控件的示例:


Private WithEvents myCtrl As MyWebUserControl 
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    myCtrl = Page.LoadControl("~/MyWebUserControl.ascx")
    Pnl_ForDisplayingMyControl.Controls.Add(myCtrl)
End Sub 
您必须在Page_Init()方法中加载该控件,否则您的Web用户控件的ViewState将无法正确加载,并且您将无法使用它。

From: https://bytes.com/topic/asp-net/insights/750415-how-use-dynamic-controls-asp-net

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值