0

I want to take the value of agronomy either yes/no... if yes it opens another form if no it pops up a message box... just can't seem to wrap my head around how to pull that stored value from the SQL command. Any help would be great I am sure it is something super simple...

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
  • ExecuteScalar instead of ExecuteReader Commented Jun 22, 2017 at 14:22

1 Answer 1

1

Since you just need a single value use 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();
Sign up to request clarification or add additional context in comments.

5 Comments

I have the user in the database and under agronomy is set to yes... however it pops up the message box.... wonder what it would be missing?
What is the result if you run the SQL Statement in SSMS? Whats the value of agronomy in the if statement?
Just ran it and it comes back as yes for that username
And if you set a breakpoint on the "if" line then what is the value of agronomy?
(If agronomy.Trim() == "yes") fixed the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.