I have a report which can be filtered by StartDate + EndDate, BookingID, CardNumber and Amount.
These are represented with 2 date pickers and 4 textboxes (CardNumber is split into 2 textboxes) and there is a Search button to return the report. My Search click code below is working fine by I'm wondering can I combine some or all of my validation code to reduce the amount of lines of code? Most of the validation code is similar I.E checking that BookingID, CardNumber and Amount are entered as ints.
I'm aware this question is bordering on a code review, so please let me know if it should be asked elsewhere.
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;
}
}
IDataErrorInfointerface, as it supports validation of your input as well, combined with binding support on multiple presentation frameworks. On the other hand, if you are using this webbased, you might also look into this