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.
See more on this question at Stackoverflow