代码如下:
using Forks.EnterpriseServices.DomainObjects2.DQuery;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using TSingSoft.WebControls2;
namespace BWP.Web.Pages.B3PigSelfBreed.Reports.CompanySettlementSummary_
{
//继承INamingContainer接口使状态保持,防止页面刷新后控件值清空
class YearAndMonthInput:Control,INamingContainer
{
//是否允许输入为空
bool _allowNull = false;
public bool AllowNull
{
get { return _allowNull; }
set { _allowNull = value; }
}
//使用static防止每次页面加载都进行数据更新
static TextBox txt_Year=new TextBox();
static TextBox txt_Month=new TextBox();
Label lb_Year;
Label lb_Month;
protected override void CreateChildControls()
{
base.CreateChildControls();
//添加年和月的输入框以及文本控件
//txt_Year = new TextBox();
txt_Year.Width = 30;
if (txt_Year.Text == "")
{
txt_Year.Text = DateTime.Now.Year.ToString();
}
Controls.Add(txt_Year);
lb_Year = new Label();
lb_Year.Text = "年";
Controls.Add(lb_Year);
//txt_Month = new TextBox();
txt_Month.Width = 30;
if (txt_Month.Text == "")
{
txt_Month.Text = DateTime.Now.Month.ToString();
}
Controls.Add(txt_Month);
lb_Month = new Label();
lb_Month.Text = "月";
Controls.Add(lb_Month);
}
/// <summary>
/// 通过输入年月变成该年月的第一天
/// </summary>
/// <returns></returns>
DateTime? GetValue()
{
EnsureChildControls();
if (!string.IsNullOrEmpty(txt_Year.Text) && !string.IsNullOrEmpty(txt_Month.Text))
{
int year = 0;
int month = 0;
if (int.TryParse(txt_Year.Text, out year) && int.TryParse(txt_Month.Text, out month))
{
if (year <= DateTime.Now.Year && (month > 0 && month < 13))
{
return new DateTime(year, month, 1);
}
else
{
throw new Exception("输入年份不能大于今年,输入月份必须在1-12之间!");
}
}
else
{
throw new Exception("请输入数字!");
}
}
else
{
if (!_allowNull)
{
throw new Exception("输入的年月不能为空!");
}
}
return null;
}
/// <summary>
/// 进行的操作
/// </summary>
/// <param name="query"></param>
/// <param name="dateExpression"></param>
public void AddConditions()
{
//随意
}
}
}