Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Experts,

I am using CellValidating Event to get the oldvalue of a column of a datagridview.My code is as below;
C#
private void dgvTnasctn_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
       {
           if (!bchk)
           {
               oldValue = Convert.ToInt32(dgvTnasctn[e.ColumnIndex, e.RowIndex].Value);
               if (e.FormattedValue != "")
               {
                   iold = oldValue;
                   inew = Convert.ToInt32(e.FormattedValue);
               }
               else
               {

                   newValue = 0;
               }
           }
       }


in above code Iam facing problem,while clicking anywhere in the gridview it shows the error "Input string was not in correct format" near
C#
"inew = Convert.ToInt32(e.FormattedValue);"


I am stuck here so anybody help me please..
Posted
Updated 18-Oct-12 19:46pm
v2

1 solution

inew = Convert.ToInt32(e.FormattedValue);

gives error because
you have handle this condition e.FormattedValue but not this,
e.FormattedValue that contains alphabet or special character (except +-.)

which can not be convert in to Int32

so,
check e.FormattedValue before converting in to int32
like this
C#
if (e.FormattedValue.Trim() != "")// check it is empty
              {
                  if IsNumeric(e.FormattedValue.Trim())//check it contains char instead of numbers
                  {
                     iold = oldValue;
                     inew = Convert.ToInt32(e.FormattedValue.Trim());
                  }
              }

C#
public static Boolean IsNumeric(string stringToTest)
{
    int result;
    return int.TryParse(stringToTest, out result);
}

Happy Coding!
:)
 
Share this answer
 
v3
Comments
Shivani Dash 19-Oct-12 3:50am    
Hii....Thanks 4 help...bt juz tell me 1 thg y ds 2nd 1?
Aarti Meswania 19-Oct-12 3:53am    
replace your similar if condition block with
if (e.FormattedValue.Trim() != "")
{
if IsNumeric(e.FormattedValue.Trim())
{
iold = oldValue;
inew = Convert.ToInt32(e.FormattedValue);
}
}

and

copy this New function in your page
public static Boolean IsNumeric(string stringToTest)
{
int result;
return int.TryParse(stringToTest, out result);
}
because it is used in if condition Line no. 3
I have highlight in solution see updated solution please


Shivani Dash 19-Oct-12 4:05am    
bt its nt taking Trim() after e.formattedvalue
Aarti Meswania 19-Oct-12 4:17am    
yes .trim
will remove white spaces
e.g.
" a " after trim -> "a"

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