Click here to Skip to main content
14,239,046 members
Rate this:
Please Sign up or sign in to vote.
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)
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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
lester555 24-Oct-10 14:57pm
its make the same error
Rate this:
Please Sign up or sign in to vote.

Solution 2

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:
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100