我有 WebUserControl,它由 3 个 DropDownLists(日/月/年)组成。它具有公共属性 DateTime BirthDate。我在 Page (Page_Load) 上动态创建了这个 WebUserControl。我希望能够更改加载的 WebUserControl 中的数据并使用页面上的按钮保存它。
WebUserControl 代码:
public DateTime BirthDate { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
DropDownList dd = new DropDownList();
DropDownList dm = new DropDownList();
DropDownList dy = new DropDownList();
this.Controls.Add(dd);
this.Controls.Add(dm);
this.Controls.Add(dy);
dd.Items.Add(new ListItem("day","0"));
dm.Items.Add(new ListItem("month", "0"));
dy.Items.Add(new ListItem("year", "0"));
dd.Items.AddRange(GetNumericValues(1, 31).ToArray());
dm.Items.AddRange(GetNumericValues(1, 12).ToArray());
int yearNow = DateTime.Now.Year;
dy.Items.AddRange(GetNumericValues(yearNow - 100, yearNow - 17).ToArray());
dd.DataBind();
dm.DataBind();
dy.DataBind();
if (BirthDate != DateTime.MinValue)
{
dd.SelectedValue = BirthDate.Day.ToString();
dm.SelectedValue = BirthDate.Month.ToString();
dy.SelectedValue = BirthDate.Year.ToString();
}
else
{
dd.SelectedValue = "0";
dm.SelectedValue = "0";
dy.SelectedValue = "0";
}
}
private List<ListItem> GetNumericValues(int from, int to)
{
List<ListItem> n = new List<ListItem>();
for (int i = from; i <= to; i++)
{
n.Add(new ListItem(i < 10 ? "0" + i.ToString() : i.ToString()));
}
return n;
}
页面代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BirthDateWebUserControl bc = new BirthDateWebUserControl();
PanelForm.Controls.Add(bc);
ViewState["BirthDateWebUserControl"] = bc;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
BirthDateWebUserControl bc = (BirthDateWebUserControl)ViewState["BirthDateWebUserControl"];
LabelResult.Text = bc.BirthDate.ToString("dd/MM/yy");
}
我做错了什么?
谢谢