asp.net(c#)动态创建一个文本框和按钮并取得文本框的值

using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //创建一个文本框
        TextBox tbxName = new TextBox();
        tbxName.ID = "tbxName";
        tbxName.Text = "OK";
        this.form1.Controls.Add(tbxName);

        //创建一个按钮
        Control c = ParseControl("<asp:Button Text = '按我' ID = 'myButton' runat = 'server' />");
        this.form1.Controls.Add(c);

        //创建一个按钮事件
        Button myButton = (Button)Page.FindControl("myButton");
        myButton.Command += new CommandEventHandler(this.myButton_Click);

    }

    protected void myButton_Click(Object sender, EventArgs e)
    {
        //真没想到要这样来取得文本框的值,这也证明了我是菜鸟
        TextBox t = (TextBox)Page.FindControl("tbxName");
        Response.Write(t.Text);
    }
}

你可能感兴趣的:(asp.net)