【问题标题】:How to find a control inside an asp.net calendar control如何在 asp.net 日历控件中找到控件
【发布时间】:2011-12-14 05:03:35
【问题描述】:

在dayrender事件中添加控件后,以后有没有办法找到该控件?我试过了

calendar.FindControl("lblSample")

但没有成功。

这里是我的一些代码更清楚:

protected void calSample_DayRender(object sender, DayRenderEventArgs e)
{
    Label lblSample = new Label();
    lblSample.ID = "lblSample";
    lblSample.Text = "Sample";
    e.Cell.Controls.Add(lblSample);
}

在一天的渲染事件和页面完全加载之后,我有一个链接按钮事件,我尝试在其中取回控件

protected void lbtnSave_Click(object sender, EventArgs e)
{
    //Not working
    Label lblSample = calSample.FindControl(lblSample);

    //Also can't get to work, this was using Ross' suggestion and the recursive find function he wrote about. I'm probably just not using it correctly.
    Label lblSample = ControlFinder.FindControl<Label>(calSample, "lblSample");
}

【问题讨论】:

  • FindControl 不会递归搜索,因此您需要自己创建不仅搜索当前子节点,还搜索其中任何容器的子节点。
  • 您可能需要通过多个层进行递归,例如如果你的表单有一个 asp:Panel 有你的控制,你需要导航 Form => Panel => Control.

标签: c# asp.net .net findcontrol


【解决方案1】:

问题是因为控件直到 dayrender 方法才添加到页面中 - 这意味着您无法在回发时获得对它的引用。使用 Page.Request.Params 集合,OP 能够在回发中获取值。


问题是查找控件不是递归的,并且您想要的控件可能在另一个控件中。

这将向您展示如何创建一个有用的递归查找控制方法:http://stevesmithblog.com/blog/recursive-findcontrol/

或者,如果您发布日历控件代码,我可能会为您提供更多帮助。

罗斯

【讨论】:

  • 感谢罗斯的文章,我将在我的一些项目中使用它。我对我的问题进行了编辑,并尝试将此功能用于我的日历问题,但没有成功。你能告诉我哪里出错了吗?
  • 好的,这里的问题是在按下按钮时标签尚未添加到日历中。当你拿到标签时,你实际上想对它做什么?
  • 我实际上是在我的真实代码中添加一个下拉列表并尝试检索选定的值。我认为你是对的,linkbutton 事件发生在 dayrender 事件之前,所以我的控件被清除了。我仍然不知道如何解决这个问题......
  • 我正在努力为您找到一个不错的解决方案,但我正在苦苦挣扎。我能想到的最好的方法是检查 Page.Request.Params 字符串以选择 id...不理想。
  • 这个解决方案最终对我来说非常棒,在我的保存点击中,我只是按照你所说的 Page.Request.Params.GetValues("ddlSample") 进行,我得到了我需要的值。您想将此作为答案提交吗?
【解决方案2】:

这个答案是因为罗斯上面的评论告诉我我可以使用 Page.Request.Params 来找到我所追求的价值。这不是最干净的解决方案,但它有效!

如果在日渲染事件中向日历控件添加下拉列表

    protected void calSample_DayRender(object sender, DayRenderEventArgs e)
    {
        DropDownList ddlSample = new DropDownList();
        ddlSample.ID = "ddlSample";
        ddlSample.DataSource = sampleDS;
        ddlSample.DataBind();
        e.Cell.Controls.Add(ddlSample);
    }

你可以像这样取回选择的值,当然我需要进行更多的检查来验证下拉列表是否存在,但是你得到了图片

    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        string sampleID = Page.Request.Params.GetValues("ddlSample")[0];
    }

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多