Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

    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;
      }

so i cant find the fileupload at run time

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
339 views
Welcome To Ask or Share your Answers For Others

1 Answer

You must recreate dynamically created controls on every postback. So store the number of already created controls in ViewState or Session and recreate them during Page_Init or Page_Load(at the latest). Assign the same ID as before so that events are triggered correctly and values can be reloaded from ViewState.

For example:

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;
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...