Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

asp.net - find control at runtime

    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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...