protected void Button1_Click(object sender, EventArgs e)
{
FileUpload F = new FileUpload { ID = "FF" };
PlaceHolder1.Controls.Add(F);
}
protected void Button2_Click(object sender, EventArgs e)
{
FileUpload FU = (FileUpload)PlaceHolder1.FindControl("FF");
Label1.Text = Fu.filename;
}
所以我无法在运行时找到文件上载
答案 0 :(得分:3)
您必须在每次回发时重新创建动态创建的控件。 因此,在ViewState或Session中存储已创建的控件的数量,并在Page_Init或Page_Load(最迟)中重新创建它们。分配与以前相同的ID,以便正确触发事件,并从ViewState重新加载值。
例如:
private Int32 ControlCount {
get {
if (ViewState("ControlCount") == null) {
ViewState("ControlCount") = 0;
}
return (Int32)ViewState("ControlCount");
}
set { ViewState("ControlCount") = value; }
}
private void Page_Load(object sender, System.EventArgs e)
{
if (ControlCount != 0) {
RecreateControls();
}
}
private void RecreateControls()
{
addControls(ControlCount);
}
private void addControls(Int32 count)
{
for (Int32 i = 1; i <= count; i++) {
FileUpload F = new FileUpload { ID = "FF_" + i };
PlaceHolder1.Controls.Add(F);
}
}
Protected void Button1_Click(object sender, System.EventArgs e)
{
addControls(1);
ControlCount ++;
}
protected void Button2_Click(object sender, EventArgs e)
{
if( ControlCount != 0 ){
// find for example the first FileUpload control
var index = 1;
FileUpload FF1 = (FileUpload)PlaceHolder1.FindControl("FF_" + index);
Label1.Text = FF1.filename;
}
}