阅读文章

动态添加控件并获取其值

[日期:2007-11-27] 来源:  作者: [字体: ]

     注意:
  1.aspx页面<%Page%>里必须添加EnableViewState="true",
  使动态添加的控件状态可保存
  2.动态添加的控件最好放在容器上(这里用Panel这个容器)
  3.必须设置动态控件的ID,否则获取不到该控件
  
  建议:运用ASP.net Ajax会有更好的用户体验效果
  例子:
  test2.ASPx:
  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test2.ASPx.cs"
  Inherits="Test2" Title="Untitled Page" EnableViewState="true" %>
   <asp:Panel ID="Panel2" runat="server" Height="50px" Width="446px">
   <asp:Label ID="Label1" runat="server" Text="Name1:"></asp:Label>
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   <asp:Label ID="Label2" runat="server" Text="Address1:"></asp:Label>
   <asp:TextBox ID="TextBox2" runat="server" Width="149px"></asp:TextBox><br />
   </asp:Panel>
   <asp:Button ID="btnAddAjax" runat="server" Text="Add" OnClick="btnAddAjax_Click" />
  <asp:Button id="btnShow" onclick="btnShow_Click" runat="server" Text="Show" />
  <asp:Label id="lblMsg" runat="server">No Value</asp:Label>
  
  
  
  test2.ASPx.cs
  
  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 Test2 : System.Web.UI.Page
  {
   protected void Page_Load(object sender, EventArgs e)
   {
  
   if(ViewState["txtName2"] != null && (bool)ViewState["txtName2"])
   {
   CreateMyControls();
   }
  
  
   }
  
   protected void btnAddAjax_Click(object sender, EventArgs e)
   {
   CreateMyControls();
   }
   protected void btnShow_Click(object sender, EventArgs e)
   {
   if(ViewState["txtName2"]!=null)
   {
   TextBox txtName2 = Panel2.FindControl("txtName2") as TextBox;
   if(txtName2 != null)
   lblMsg.Text = "Name2= " + txtName2.Text;
   }
  
   if(ViewState["txtAddr2"]!=null)
   {
   TextBox txtAddr2 = Panel2.FindControl("txtAddr2") as TextBox;
   if(txtAddr2 != null)
   lblMsg.Text += " Addr2= " + txtAddr2.Text;
   }
  
  
   }
  
   private void CreateMyControls()
   {
   Label lblName2 = new Label();
   lblName2.Text = "Name2:";
  
   TextBox txtName2 = new TextBox();
   //设置ID,否则不能获取到值
   txtName2.ID = "txtName2";
   //可视状态,否则PostBack后动态添加的控件会不见
   ViewState["txtName2"]= true;
  
   Label lblAddr2 = new Label();
   lblAddr2.Text = "Addr2:";
    


阅读:
录入:blue1000

评论 】 【 推荐 】 【 打印
上一篇:C#发送Email邮件方法总结
下一篇:ASP.NET 3.5 的 ListView 控件与 CSS Friendly
相关文章      
本文评论
  放屁   (赌东道 ,2008-05-06 )
发表评论


点评: 字数
姓名:

  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款