我正在尝试让我的代码检查是否已经为今天的日期输入了一个数字。原因是整个书中的docketnumbers重复,有点像抽奖券。我不希望在同一天多次将相同的数字输入数据库。
现在是我的代码
string thisday = DateTime.Now.ToString("MM/dd/yyyy");
然后检查
public void button11_Click(object sender, EventArgs e)
{
string thisday = DateTime.Now.ToString("MM/dd/yyyy");
errorProvider1.Clear();
Data.docnum = txtDisplay.Text;
if (txtDisplay.Text == "")
{
errorProvider1.SetError(txtDisplay, "Enter Docket Number");
return;
}
using (var db = new DocketsDataContext())
{
var docketCheck = from q in db.Dockets where q.Status== "Ca" select q;
string message = "";
foreach (var d in docketCheck)
{
message += String.Format(" DocketNum {0} - Status {1} - TimeRaised {2} - Thisday {3}\r\n", d.DocketNum, d.Status, d.TimeRaised, thisday);
}
MessageBox.Show(message);
var complete = from q in db.Dockets
where q.DocketNum == txtDisplay.Text && q.Status.Equals("CL") //&& q.TimeRaised.Contains(thisday)
select q;
var cancelcheck = from q in db.Dockets
where q.DocketNum == txtDisplay.Text && q.Status.Equals("Ca") && q.TimeRaised.Equals(thisday)
select q;
var docketcheck = from q in db.Dockets
where q.DocketNum == txtDisplay.Text && q.Status.Equals("O") //&& q.TimeRaised.Contains(thisday)
select q;
var statuscheck = from q in db.Dockets
where q.DocketNum == txtDisplay.Text && q.Status.Equals("Ea") //&& q.TimeRaised.Contains(thisday)
select q;
if (cancelcheck.Count() >= 1)
{
MessageBox.Show(@"Match Found");
txtDisplay.Clear();
txtDisplay.ReadOnly = false;
var cancel = new Cancel();
cancel.ShowDialog(this);
}
else if (complete.Count() >= 1)
{
txtDisplay.Clear();
txtDisplay.ReadOnly = false;
var cat = new Docerror();
cat.ShowDialog(this);
}
else if (statuscheck.Count() >= 1)
{
txtDisplay.Clear();
txtDisplay.ReadOnly = false;
var cat = new Category();
cat.ShowDialog(this);
}
else if (docketcheck.Count() >= 1)
{
txtDisplay.Clear();
txtDisplay.ReadOnly = false;
var engs = new EngStart();
engs.ShowDialog(this);
}
else
{
var sub = new machinesel();
txtDisplay.Clear();
sub.ShowDialog(this);
}
}
}
当今天与今天的日期匹配时,它应该触发取消功能,但事实并非如此;任何想法?
杰伊答案 0 :(得分:1)
您正在使用String
来评估DateTime
,这将永远不会返回true。
请尝试使用以下内容:
var cancelCheck =
(from q in db.Dockets
where
q.DocketNum == txtDisplay.Text &&
q.Status.Equals("Ca") &&
q.TimeRaised.Date == DateTime.Now.Date
select q).Any();
另外,请使用Any()
而不是Count() > 0
答案 1 :(得分:0)
在您的查询中,您可以执行以下操作:
from q in db.Dockets
where q.DocketNum == txtDisplay.Text
&& q.Status.Equals("CL")
&& (q.TimeRaised - DateTime.Today).Hours >= 0
&& !(q.TimeRaised > DateTime.Today.AddDays(1))
select q;
不确定是否可以添加具有未来日期的记录,因此我添加了“ DateTime.Today.AddDays(1)” 该逻辑基于比较两个日期返回的TimeSpan类:
TimeSpan ts = DateTime.Now - DateTime.Now.AddYears(-1);
Console.WriteLine(ts.Days);
哪会给你365天的差异。