Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
when i use this code vs shows following error : Specified cast is not valid. with title : InvalidCastExeption was unhandled
 private void TradeLog_Load_1(object sender, EventArgs e)
        {
sqlDataAdapter1.Fill(dataSet11);
decimal allwin;
            decimal win = 0;
            decimal self;

            for (int i = 0; i < DgvLog.Rows.Count; i++)
            {
                self = (decimal)DgvLog.Rows[i].Cells["selfPriceDataGridViewTextBoxColumn"].Value;
                win += self;
            }

            allwin = sum - win;
            label7.Text = win.ToString();
        }


what is incorrect i think it must be work very good. cant find any mistake
Posted

Try Convert.ToDecimal(DgvLog.Rows[i].Cells["selfPriceDataGridViewTextBoxColumn"].Value); instead.

Convert.ToDecimal will try to parse your string - a cast using decimal (as you have done) is useful when the item being cast is already a number.
 
Share this answer
 
v2
Comments
lester555 24-Oct-10 14:57pm    
its make the same error
Issue must be here:
self = (decimal)DgvLog.Rows[i].Cells["selfPriceDataGridViewTextBoxColumn"].Value;
A simple use of DEBUGGER must have told you about the line and the reason.

Error simply means that the conversion that you are trying to make is not valid. In above line, you are forcing a conversion (type casting) of some cell value into decimal which is not right.

If you are sure that the value of the cell is of decimal format then you can try:
Convert.ToDecimal(DgvLog.Rows[i].Cells["selfPriceDataGridViewTextBoxColumn"].Value);
 
Share this answer
 
Comments
lester555 24-Oct-10 14:58pm    
it does not work selfPrice in the sql table is decimal type.
Sandeep Mewara 24-Oct-10 15:44pm    
1. Use DEBUGGER and see if and what is the value in 'DgvLog.Rows[i].Cells["selfPriceDataGridViewTextBoxColumn"].Value'
2. Looks like it's not necessary that you convert it into Decimal at frontend. If the cell has valid number then try Convert.ToDouble(DgvLog.Rows[i].Cells["selfPriceDataGridViewTextBoxColumn"].Value);

P.S.: Make sure you have value before conversion.
lester555 24-Oct-10 16:42pm    
i have done. In table selfPrice was empty. that was problem
Sandeep Mewara 25-Oct-10 1:33am    
Thats what I told you! A valid value for conversion. :)
Good to know its resolved now.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900