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

Categories

0 votes
327 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...