发现在运行时控制 [英] find control at runtime

查看:95
本文介绍了发现在运行时控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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

推荐答案

您必须重新创建动态创建在每一个回传控制。
因此,存储在ViewState中或会话已经创建控件的数量和Page_Init或的Page_Load(最晚)中重新创建它们。指定同一个ID像以前这样的事件触发正确和价值观可以从ViewState中重新加载。

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.

  • Dynamically created controls are wiped out on button click (repeating myself)
  • Page Life Cycle Overview
  • Dynamically Created Controls in ASP.NET

例如:

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

这篇关于发现在运行时控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆