我的报告可以按StartDate
+ EndDate
,BookingID
,CardNumber
和Amount
进行过滤。
这些用2个日期选择器和4个文本框表示(CardNumber
分成2个文本框),并且有一个Search
按钮可以返回报告。我的搜索点击代码工作正常,我想知道我可以将部分或全部验证代码合并以减少代码行数吗?大多数验证代码都类似于I.E,检查BookingID
,CardNumber
和Amount
是否以整数形式输入。
我知道这个问题与代码审核有关,所以请告诉我是否应该在其他地方询问。
protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
{
lblInputMessage.Visible = false;
DateTime dtStart, dtEnd;
bool isGood = DateTime.TryParse(txtEndDate.Text, out dtEnd);
if (DateTime.TryParse(txtStartDate.Text, out dtStart))
{
if (txtEndDate.Text.Trim() == "")
{
dtEnd = DateTime.Now;
isGood = true;
}
}
if (txtBookingID.Text.Length > 0)
{
int newBookingID;
if (int.TryParse(txtBookingID.Text, out newBookingID))
{
isGood = true;
}
else
{
lblInputMessage.Visible = true;
lblInputMessage.Text = "Please enter a valid BookingID.";
return;
}
}
if (txtAmount.Text.Length > 0)
{
int newAmount;
if (int.TryParse(txtAmount.Text, out newAmount))
{
isGood = true;
}
else
{
lblInputMessage.Visible = true;
lblInputMessage.Text = "Please enter a valid Amount.";
return;
}
}
if (txtCardNumber1.Text.Length > 0 || txtCardNumber2.Text.Length > 0)
{
int newCardNumber1;
int newCardNumber2;
if (int.TryParse(txtCardNumber1.Text, out newCardNumber1) && (int.TryParse(txtCardNumber2.Text, out newCardNumber2)))
{
isGood = true;
}
else
{
lblInputMessage.Visible = true;
lblInputMessage.Text = "Please enter a valid Card Number.";
return;
}
}
if (isGood)
{
if (dtStart > dtEnd)
{
lblInputMessage.Visible = true;
lblInputMessage.Text = "End Date must be greater than Start Date.";
return;
}
lblInputMessage.Visible = false;
LoadGridData(true);
ajaxCollapsiblePanel1.Collapsed = true;
ajaxCollapsiblePanel1.ClientState = "true";
pnlContainer.Visible = true;
}
else
{
lblInputMessage.Visible = true;
lblInputMessage.Text = "Please enter a valid date.";
return;
}
}
答案 0 :(得分:4)
您可以修改它以使用IDataErrorInfo并执行类似的操作。
public string Error
{
get { return String.Empty; }
}
public string this[string columnName]
{
get
{
String errorMessage = String.Empty;
switch (columnName)
{
case "Variable1":
if (String.IsNullOrEmpty(Variable1))
{
errorMessage = "Variable1 is required";
}
break;
case "Variable2":
if (Variable2 < 10)
{
errorMessage = "Variable2 can't be less than 10";
}
break;
}
return errorMessage;
}
}
本教程https://tarundotnet.wordpress.com/2011/03/03/wpf-tutorial-how-to-use-idataerrorinfo-in-wpf/涵盖了基础知识。