拉SQL值然后运行If / Else语句

时间:2017-06-22 14:20:21

标签: c# sql if-statement

我想把农学的价值看为是/否......如果是,它会打开另一种形式,如果没有它弹出一个消息框...似乎无法绕过如何拉动存储SQL命令的值。任何帮助都会很棒我确信它是超级简单的......

SqlConnection cn = new SqlConnection(@"Data Source=*****;Initial Catalog=agSale;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("SELECT agronomy from logins where userName = @userName", cn);
        cmd.Parameters.AddWithValue("userName", nameLabel.Text);
        cn.Open();
        SqlDataReader reader = cmd.ExecuteReader();


        if (agronomy == "yes") 
             new agronomy().Show();
        else
            MessageBox.Show("You can't access this part of the program.  For questions call 867-5309.");


        cn.Close();

1 个答案:

答案 0 :(得分:1)

由于您只需要使用一个值ExecuteScalar

SqlConnection cn = new SqlConnection(@"Data Source=*****;Initial Catalog=agSale;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("SELECT agronomy from logins where userName = @userName", cn);
        cmd.Parameters.AddWithValue("userName", nameLabel.Text);
        cn.Open();
        string agronomy = cmd.ExecuteScalar()?.ToString();


        if (agronomy == "yes") 
             new agronomy().Show();
        else
            MessageBox.Show("You can't access this part of the program.  For questions call 867-5309.");


        cn.Close();