none
Why is SQL not returning a single value as text? RRS feed

  • Question

  • Why is this not returning a number to my text box? I am trying to take a the price from the column "NFF" of the "MFD" row and return it as the textbox text. This is a single table database.  The text box should return 555

     private void button1_Click(object sender, EventArgs e)
    
        {
            string command = "SELECT NFF FROM dbo.Prices WHERE Item ='MFD'";
    
            try
            {
                SqlConnection SQLCON = new SqlConnection(Properties.Settings.Default.PricesConnectionString);
                SQLCON.Open();
                SqlCommand SQLCommand = new SqlCommand();
                SQLCommand.CommandType = CommandType.Text;
    
                SQLCommand.CommandText = command;
                Int32 price = (Int32)SQLCommand.ExecuteScalar();
    
                txtbox1.Text = price.ToString();
                return;
    
            }
            catch
            {
    
            }

    example of my database:

    Item    MAJOR   MINOR   NFF
    RAD     199     250     300
    MFD     300     454     66969
    Sunday, March 29, 2015 4:25 AM

Answers

  • What else does it return if not 555 (or 66969 as in the table)? A differnt value, or do you get an exception? Hard to say because you have an empty catch block that just swallows every problem leaving you clueless. So I suggest to handle the exception, at least by showing the exception message.

    Armin

    • Edited by Armin Zingler Sunday, March 29, 2015 10:17 AM
    • Marked as answer by Tyberius13 Sunday, March 29, 2015 2:03 PM
    Sunday, March 29, 2015 10:17 AM

All replies

  • What else does it return if not 555 (or 66969 as in the table)? A differnt value, or do you get an exception? Hard to say because you have an empty catch block that just swallows every problem leaving you clueless. So I suggest to handle the exception, at least by showing the exception message.

    Armin

    • Edited by Armin Zingler Sunday, March 29, 2015 10:17 AM
    • Marked as answer by Tyberius13 Sunday, March 29, 2015 2:03 PM
    Sunday, March 29, 2015 10:17 AM
  • When not using try:

    I reverie "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll"

    referring to the end of the "int price = Convert.ToInt32(SQLCommand.ExecuteScalar());"

    Sunday, March 29, 2015 1:38 PM
  • I guess the exception has also a message text. Look at it to see the reason for the problem. You did not specify a connection for the command object.

    Armin

    Sunday, March 29, 2015 1:52 PM