1

The below code snippet pulls a pack size column from my table but am using getString which I get an error then now see is an issue because the column am pulling is of decimal type. How would I cast my snippet to accept the decimal values?

try
        {
            string connectionString = "Data Source=CMDLAP121\\SQLEXPRESS;Initial Catalog=TESTBAR;Integrated Security=True";

            string query = "SELECT * FROM BCODEREF WHERE BAR_CODE = '" + comboBox1.Text + "';";
            string mystring = query;
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                string spo = dr.GetString(dr.GetOrdinal("PACKSIZE"));
                ponum.Text = spo;
            }
        }

        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
Artem
  • 2,084
  • 2
  • 21
  • 29
AJ26
  • 501
  • 4
  • 15
  • 1
    You are making redundant things. It is much easier: decimal packSize= 0; decimal.TryParse(dr["PACKSIZE"].ToString(), out packSize); And yeah, the comment regarding sql injection is very important to deliver – Artem Jul 07 '17 at 14:19
  • @Prdp ok, noted. – AJ26 Jul 07 '17 at 14:27
  • @artem noted. Will fix as to avoid SQL injection. One more question, how would I assign your solution to my textBox as shown in my original post? – AJ26 Jul 07 '17 at 14:33
  • 2
    ponum.Text = packSize.ToString("0.00"); //specify format you need. See here for details https://stackoverflow.com/questions/8125492/converting-decimal-to-string-with-non-default-format – Artem Jul 07 '17 at 14:36
  • @Artem I understand the point you are making but in the case of my data, how do I actually pull the "PACKSIZE" column data from my table within my database which is of decimal type? – AJ26 Jul 07 '17 at 14:52
  • @ARTEM my apologies. I figured it out. thank you – AJ26 Jul 07 '17 at 15:03

1 Answers1

1

Parse to decimal first and convert to a string with the format you need:

decimal packSize= 0; 
decimal.TryParse(dr["PACKSIZE"].ToString(), out packSize);

ponum.Text = packSize.ToString("0.00");  //specify format you need

See this post for details of how to set up appropriate string format

Artem
  • 2,084
  • 2
  • 21
  • 29