Search code examples
c#asp.net.netfindcontrol

How to find a control inside an asp.net calendar control


After adding a control in the dayrender event, is there a way to find the control later? I have tried

calendar.FindControl("lblSample")

but without success.

Here is some of my code to be more clear:

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

After the day render event and the page loads completely, I have a link button event where I try and get the control back

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

Solution

  • This answer is because of Ross' comment above showing me that I could use the Page.Request.Params to find the value I was after. It's not the cleanest solution but it works!

    If you add a dropdownlist to a calendar control in the day render event

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

    You can get the selected value back like this, of course I need to put in more checks to verify that the dropdownlist exists, but you get the picture

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