//原帖:http://topic.csdn.net/t/20051019/11/4336067.html
//我只摘下了,對我有用的東西。
//學習動態創建控件和取值的方法
代碼如下:
for(int i=0;i<5;i++)
{
TextBox tbcz=new TextBox();
tbcz.ID="cz"+i;
this.Panel2.Controls.Add(tbcz);
}
用戶輸入值後,我去對應控件裏面的值出錯!
取值代碼:
for(int i=0;i<5;i++)
{
string cz_s="cz"+i.ToString();
string cz_t=((TextBox)Page.FindControl(cz_s)).Text.Trim(); //這句出錯
.......
}
-------------------------------------------------------------------------
4 樓daishengs(橫舟擺渡)回覆於 2005-10-19 11:48:51 得分 2
我以前是這樣用的,你可以修改一下
private static void FindTextBox(System.Web.UI.Control oControl,string ControlID,string ControlValue)
{
if(oControl.HasControls())
{
foreach (System.Web.UI.Control oChildControl in oControl.Controls)
{
if( (oChildControl.ID==ControlID)&&(oChildControl is System.Web.UI.WebControls.TextBox))
{
((System.Web.UI.WebControls.TextBox)oChildControl).Text=ControlValue;
//oControl = oChildControl;
//((System.Web.UI.WebControls.TextBox)oControl).Text=ControlValue;
return;
}
FindDataGrid(oChildControl,ControlID,ControlValue);
}
}
}
public static void SetControl(System.Web.UI.Control Page,string ControlID,string ControlValue)
{
FindTextBox(Page,ControlID,ControlValue);
}
-------------------------------------------------------------------------
6 樓webdiyer(.net資源精華—www.dotneturls.com)回覆於 2005-10-19 11:56:55 得分 2
動態創建控件的語句在什麼地方?如果是在Page_Load方法中,
不能放在if(!Page.IsPostBack)塊中,
因爲動態創建的控件無法正確保存和獲取視圖狀態,
所以頁面每次加載都必須重新創建才行。
-------------------------------------------------------------------------
8 樓vzxq(靈感人)回覆於 2005-10-19 13:57:53 得分 15
應該是你提交後,找不到動態生成的控件了
用這個方法試試
TextBox txt = new TextBox();
for(int i=0;i<5;i++)
{
string cz_t=Request.Form["txt"+i];
.......
}
-------------------------------------------------------------------------
12 樓anheizhizi(目標:★★★★★)回覆於 2005-10-19 17:01:03 得分 2
生成控件的代碼不要寫在
if(!Page.IsPostBack) 裏或 用Request.Form[ID] 得到