繁体   English   中英

如何使用C#在If语句中使用多个运算符

[英]How to use more than one Operator in an If Statement using C#

我想在if语句中使用=,>,&&等多个运算符。 如果(strAuthReqDate == null && strDate <strExpectedSubDate),则我只想在此条件为true时发送电子邮件。 所以我认为我的“小于运算符”是错误的,请让我知道我在这里做错了什么。 谢谢

这是我的代码:

foreach (GridViewRow gr in GridView1.Rows)
{
    CheckBox cb = (CheckBox)gr.FindControl("chkItem");
    if (cb.Checked)
    {
        // string strID = gr.Cells[0].Text;
        string strExpectedSubDate = gr.Cells[3].Text;
        string strAuthReqDate = gr.Cells[8].Text;
        string strDate = Convert.ToString(System.DateTime.Now);
        if (strAuthReqDate == null && strDate < strExpectedSubDate)
        {
            send email();
        }
    }
 }

尝试使用此代码比较日期

DateTime strExpectedSubDate = DateTime.ParseExact(gr.Cells[3].Text, dateformat);
DateTime strAuthReqDate = DateTime.ParseExact(gr.Cells[8].Text, dateformat);
DateTime strDate = System.DateTime.Now;
if (strAuthReqDate == null && strDate < strExpectedSubDate)
{
}

首先, Cells[i].Text永远不会为null,因此您应该使用String.IsNullOrWhiteSpce或什至更好,请尝试将其String.IsNullOrWhiteSpce转换为DateTime

您无法比较字符串,并且不能期望将它们像DateTimes一样对待,C#不是VB6。 因此,首先将它们转换为Datetimes:

DateTime ExpectedSubDate;
string strExpectedSubDate = gr.Cells[3].Text;
if(DateTime.TryParse(strExpectedSubDate, out ExpectedSubDate))
{
    DateTime AuthReqDate;
    string strAuthReqDate = gr.Cells[8].Text;
    if(!DateTime.TryParse(strAuthReqDate, out AuthReqDate))
    {
        if(DateTime.Now < ExpectedSubDate)
        {
            SendMail();
        }
    }
}

您的代码比较文本日期,而不是实际日期。 您需要比较DateTime对象以使其按预期工作!

这是因为strDate和strExpectedSubDate是字符串。 因此,您不能使用小于运算符来比较它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM