简体   繁体   中英

Decimal to String “Specified cast is not valid”

private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand(@"Select * FROM PRODUCTS where [PRODUCT CODE] = '" + comboBox4.Text + "'", con);
    SqlDataReader myReader;
    try
    {
        con.Open();
        myReader = cmd.ExecuteReader();

        while (myReader.Read())
        {
            int decimPRICE = myReader.GetInt32(myReader.GetOrdinal("PRICE"));
            string PRICE = decimPRICE.ToString("0.00");
            textBox7.Text = PRICE;

        }
        con.Close();
    }
    catch (Exception exe)
    {
        MessageBox.Show(exe.Message);
    }
}

Its in ComboBox to Textbox

This codes is ok, but " Specified cast is not valid " is appearing when i clicked item/index in ComboBox . I dont know why.

decimPRICE is PRICE (decimal 18,2).

It sounds like you probably just want:

decimal price = reader.GetDecimal(reader.GetOrdinal("PRICE"));
textBox7.Text = price.ToString("0.00");

Basically, decimal and int aren't the same things, and if you're storing a value as a decimal, you almost certainly don't want to just lose everything after the decimal point.

Additionally, now we can see more of your code, you should stop doing this immediately :

// WARNING! WARNING! SQL INJECTION ATTACK!
SqlCommand cmd = new SqlCommand(@"Select * FROM PRODUCTS where [PRODUCT CODE] = '" + comboBox4.Text + "'", con);

This is vulnerable to SQL Injection Attacks - you should instead use parameterized SQL:

SqlCommand cmd = new SqlCommand("Select * FROM PRODUCTS where [PRODUCT CODE] = @code, con);
cmd.Parameters.Add("@code", SqlDbType.Varchar).Value = comboBox4.Text;

This should be the first thing you change - it's a gaping security hole at the moment.

You should also open the connection fresh each time, and have it (and the command, and the reader) in using statements so they are disposed appropriately.

Next, if there are multiple matching products you're only actually using the last result - is that what you want?

Next, you're only using the price - so why use SELECT * ?

Finally, this looks like a WinForms GUI or similar - in which case you shouldn't do this in the UI thread. Any long-running work should be done in a separate thread, or using asynchronous operations.

You should use GetDecimal like this:

decimal decimPRICE = myReader.GetDecimal(myReader.GetOrdinal("PRICE"));
string PRICE = decimPRICE.ToString("0.00");
textBox7.Text = PRICE;

Note that decimPRICE is now decimal instead of int .

Your exception was raised because GetInt32 can not cast a DB decimal into an Int32 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM