gpt4 book ai didi

c# - 具有多个条件的语句不返回 C# 中的预期行为

转载 作者:行者123 更新时间:2023-11-29 21:16:58 25 4
gpt4 key购买 nike

我使用 ASP.NET C# 和 MySQL 数据库。

在我的数据库表的字段 doDate 中,我可以有三个值:

  1. Null
  2. 0000-00-00
  3. 2016-03-08

我需要字段 doDate 的值为:

  1. 0000-00-00
  2. 2016-03-08

禁用了TextBox txtdoDate,我已经尝试过:

    txtdoDate1 = dr["doDate"] == DBNull.Value ? "" : dr["doDate"] == "0000-00-00" ? "0000-00-00" : Convert.ToDateTime(dr["doDate"]).ToString("dd/MM/yyyy");

if (txtdoDate1.ToString() != "")
{
txtdoDate.Text = txtdoDate1.ToString();
txtdoDate.Enabled = false;
}
else
{
txtdoDate.Enabled = true;
}

但是当字段doDate的值为:

0000-00-00

TextBox txtdoDate 已启用且为空。

你能帮我解决这个问题吗?

提前致谢。

编辑#1

protected void loadsRecord()
{
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
sql = @" SELECT ..... ; ";

using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
dr = command.ExecuteReader();

while (dr.Read())
{

txtdoDate1 = dr["doDate"] == DBNull.Value ? "" : (dr["doDate"] == "0000-00-00" ? "0000-00-00" : Convert.ToDateTime(dr["doDate"]).ToString("dd/MM/yyyy"));

if (txtdoDate1.ToString() != "")
{
txtdoDate.Text = txtdoDate1.ToString();
txtdoDate.Enabled = false;
}
else
{
txtdoDate.Enabled = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}

最佳答案

这是正确的行为,因为您正在使用以下 if 语句

if (txtdoDate1.ToString() != "")
{
txtdoDate.Text = txtdoDate1.ToString();
txtdoDate.Enabled = false;
}
else
{
txtdoDate.Enabled = true;
}

dr["doDate"] == "0000-00-00" 时,txtdoDate 中存储的值为 "0000-00-00" 不是 txtdoDate1.ToString() != ""。您必须修改 if 语句中的条件,如下所示:

if (txtdoDate1.ToString() != "" && txtdoDate1.ToString() != "0000-00-00")

关于c# - 具有多个条件的语句不返回 C# 中的预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35862166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com