我正在制作一个asp.net Web窗体应用程序。如果任何用户输入错误,则显示验证。但是,第二次当用户提供正确的输入时,代码正常工作,只有问题是错误消息不会被删除。
在页面加载功能
pnlStatus.Visible = true;
Button_Click事件写在
下面 protected void btnAffRntGoClick(object sender, EventArgs e)
{
DateTime dtFrom = new DateTime();
DateTime dtTo = new DateTime();
bool dt1 = true;
bool dt2 = true;
int result;
if (DateTime.TryParse(txtStartDate.Text, out dtFrom) == false)
{
dtFrom = new DateTime(1900, 1, 1);
dt1 = false;
}
if (DateTime.TryParse(txtEndDate.Text, out dtTo) == false)
{
dtTo = new DateTime(2100, 1, 1);
dt2 = false;
}
result = DateTime.Compare(dtTo, dtFrom);
if ((dt1 == true && dt2 == true) && result > 0)
{
lblPageStatus.Text = string.Empty;
pnlStatus.Visible = false;
DataSet ds = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(), "SPNAME",
Convert.ToInt64(ddl.SelectedValue), dtFrom.Date.ToShortDateString(), dtTo.Date.ToShortDateString(), ddl2.SelectedValue, Chk1.Checked);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
// Code to generate Excel
}
else
{
pnlStatus.Visible = true;
lblPageStatus.Text = "No data available to export.";
}
}
else
{
pnlStatus.Visible = true;
lblPageStatus.Text = "Please Check the Dates";
}
}
任何类型的帮助将不胜感激。
先谢谢
答案 0 :(得分:0)
简短回答我想您只需要在有数据时相应地更新您的控件。
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
// Code to generate Excel
pnlStatus.Visible = false;
lblPageStatus.Text = string.Empty;
}
else
{
pnlStatus.Visible = true;
lblPageStatus.Text = "No data available to export.";
}
长答案 - 您的代码应该通过一些标准进行清理和签署,以实现可读性。这可能就是你迷路的原因。可以引入其他方法来简化。以下是快速概述。此外,pnlStatus.Visible
和lblPageStatus.Text
可以使用单行代码设置在一个位置(但可读性稍差一些)。
需要考虑的事项:
让您的代码尽可能多可读(意味着任何人都可以阅读您的代码)
private const string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
protected void btnAffRntGoClick(object sender, EventArgs e)
{
var from = new DateTime(1900, 1, 1);
var to = new DateTime(2100, 1, 1);
var isValidStartDate = !DateTime.TryParse(txtStartDate.Text, out from);
var isValidEndDate = !DateTime.TryParse(txtEndDate.Text, out to);
var hasValidDates = isValidStartDate && isValidEndDate;
var hasDifference = DateTime.Compare(from, to) > 0;
var shouldCheckDates = !hasValidDates || !hasDifference;
if (shouldCheckDates)
{
pnlStatus.Visible = true;
lblPageStatus.Text = "Please Check the Dates";
return;
}
DataSet ds = SqlHelper.ExecuteDataset(connectionString,
"SPNAME",
Convert.ToInt64(ddl.SelectedValue)
, @from.Date.ToShortDateString(),
to.Date.ToShortDateString()
, ddl2.SelectedValue
, Chk1.Checked
);
var hasData = ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0;
pnlStatus.Visible = !hasData;
lblPageStatus.Text = hasData ? string.Empty : "No data available to export.";
}