AJ26
AJ26

Reputation: 501

How do I cast decimal values to string from my database?

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());
        }

Upvotes: 1

Views: 499

Answers (1)

Artem
Artem

Reputation: 2314

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

Upvotes: 1

Related Questions