C#增加连续的动态控件并取值的例子

来源:互联网 发布:微信小程序业务域名 编辑:程序博客网 时间:2024/05/16 01:18

CS CODE

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AddTextBoxSample : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        ReLoadAddedTextBoxs();
    }

    
//重新加载已经加载过的TextBox
    private void ReLoadAddedTextBoxs()
    {
            
for (int i = 1; i <= AddedTextBoxIds.Count; i++)
            {
                TextBox tb 
= new TextBox();
                tb.ID 
= i.ToString();
                Panel1.Controls.Add(tb);
            }
    }

    
private const string c_ids = "TextBoxIds";
    
/// <summary>
    
/// 纪录下动态增加的TextBox的ID值
    
/// </summary>
    private ArrayList AddedTextBoxIds
    {
        
get
        {
            
if (ViewState[c_ids] == null)
                ViewState[c_ids] 
= new ArrayList();

            
return ViewState[c_ids] as ArrayList;
        }

        
set { ViewState[c_ids] = value; }
    }

    
protected void BT_AddControl_Click(object sender, EventArgs e)
    {
        
//获取现在要增加的TextBox的ID索引
        string id = Convert.ToString(AddedTextBoxIds.Count + 1);
        
        TextBox newBox 
= new TextBox();
        newBox.Width 
= Unit.Pixel(200);
        newBox.ID 
= id;
        newBox.Text 
= "现在是增加的第" + id + "个TextBox";

        Panel1.Controls.Add(newBox);
        AddedTextBoxIds.Add(id);    
//纪录下新增加的TextBoxID,在下次PostBack时重新加载
    }
    
protected void BT_GetControlsValue_Click(object sender, EventArgs e)
    {
        
for (int i = 1; i <= AddedTextBoxIds.Count; i++)
        {
            TextBox tb 
= Panel1.FindControl(i.ToString()) as TextBox;
            
if (tb != null)
            { 
                
//这里是加载的TextBox的值
                
//tb.Text....
                
//tb.ID.....

            }
        }
    }
}

HTML CODE

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddTextBoxSample.aspx.cs" Inherits="AddTextBoxSample" %>

<!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>增加动态的TextBox,并取值的例子</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:Panel ID="Panel1" runat="server" Height="278px" Width="549px">
        
</asp:Panel>
        
<asp:Button ID="BT_AddControl" runat="server" OnClick="BT_AddControl_Click" Text="增加一个TextBoxControl" />
        
<asp:Button ID="BT_GetControlsValue" runat="server" OnClick="BT_GetControlsValue_Click"
            Text
="取得动态加载的TextBox的值" /></div>
    
</form>
</body>
</html>
原创粉丝点击