将onSelectChanged事件添加到动态创建的日历中

时间:2015-06-22 10:09:17

标签: c# asp.net user-controls

在我的.ascx用户控件中,我有一些ImageButton元素,当点击这些元素时,它们会动态创建,然后显示Calendar Element将其添加到PlaceHolder。我有三个,该函数将为从单击的ImageButton的ID创建的每个日历生成一个ID。我正在尝试为每个创建的日历动态添加SelectionChanged事件。

我在类的开头声明了一个空对象日历作为全局变量。我在onPageLoad上实例化一个新的Calendar对象,在click事件中我添加了ID,事件并将其添加到占位符。

SelectChange事件似乎不起作用。缺少什么?

public partial class admin_CaptureDate : System.Web.UI.UserControl {     protected Calendar DateCalendar;

protected void Page_Init(object sender, EventArgs e) 
{
    DateCalendar = new Calendar();
    DateCalendar.ID = "DateCalendar";
    DateCalendar.Width = 176;
    DateCalendar.SelectionChanged += Calendar_SelChanged;
}

protected void Page_Load(object sender, EventArgs e)
{

}

protected void ShowCalendar_Click(object sender, ImageClickEventArgs e) 
{
    ImageButton btnSender = (ImageButton)sender;
    string Prefix = btnSender.ID.Substring(14);
    Trace.Write("this is prefix " + Prefix);
    this.FindControl(Prefix + "PlaceHolder").Controls.Add(DateCalendar);
}
protected void Calendar_SelChanged(object sender, EventArgs e) 
{
    Calendar SelectedCalendar = (Calendar)sender;
    string SelectedDate = SelectedCalendar.SelectedDate.ToLongDateString();
    Trace.Write("this is the selected date" + SelectedDate);
}

}

仍然不起作用,事件没有附在日历上,还有什么遗失?

1 个答案:

答案 0 :(得分:0)

初始化日历,将其添加到页面的控件集合中,并在Page_Init中添加事件处理程序。事件太晚了。

protected void Page_Init(object sender, EventArgs e)
{   
    DateCalendar = new Calendar();
    DateCalendar.SelectionChanged += Calendar_SelChanged;
}

他们也必须获得与以前相同的ID。但似乎您根据此处的Button.ID更改了ID:

string Prefix = btnSender.ID.Substring(14);
DateCalendar.ID = Prefix + "Calendar";

这不起作用。如果您需要多个按钮的日历,请添加多个日历。