在c#的while循环中使用条件

本文关键字:条件 循环 while | 更新日期: 2023-09-27 18:18:44

我的c#代码有问题。

我需要验证用户名,我在while循环中使用了if条件,但问题是,即使用户名和密码不正确,它也不会执行任何语句。

我在数据库中测试了身份验证的查询,输出是正确的。

我试过这三种不同的解决方案,都没有成功。

下面是我的代码:

解决方案# 1

using (OdbcDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        int count = reader.GetInt32(0);
        if (count > 0)
        {
            Response.Write("Welcome!");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('no data.');", true);
        }
    }
}

解决方案# 2

using (OdbcDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        if (reader.HasRows)
        {
            Response.Write("Welcome!");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('no data.');", true);
        }
    }
}

解决方案# 3

using (OdbcDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        if (!String.IsNullOrEmpty(reader[0].ToString()))
        {
            Response.Write("Welcome!");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('no data.');", true);
        }
    }
}

在c#的while循环中使用条件

你的解决方案都无效。你似乎认为你的while循环总是被执行,但事实并非如此。当sql查询返回0行时,您永远不会进入while(reader.Read())循环。

基于第二个解决方案的一个简单方法可能如下所示:

using (OdbcDataReader reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        Response.Write("Welcome!");
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('no data.');", true);
    }
}

注意没有while循环。