Click here to Skip to main content
14,638,880 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am beginner in C# Windows Application.
I am saving data in sql server 2005.
I have a decimal column namely origrate in table.
I am picking data from datagridview cell.
To save data in table I convert type of datagridview cell value to decimal.
as like :

decimal iorigrate=0M;
if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["origrate"].Value.ToString()))
   iorigrate =Convert.ToDecimal(dataGridView1.Rows[i].Cells["origrate"].Value);


but I have following errors

NullReferenceException was unhandled


Kindly tell me where I am wrong.

Please help me.
Posted
Updated 6-Dec-11 15:36pm
v2
Comments
D K N T H 6-Dec-11 21:37pm
   
added pre tag
Rate this:
Please Sign up or sign in to vote.

Solution 1

You are converting dataGridView1.Rows[i].Cells["origrate"].Value to string by using ToString().
If the value is null, this will fail with the error you are getting.

Try checking for null before you apply ToString().
Debugging and stepping through code will give you an idea when you are getting this error.
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

Change your code from

decimal iorigrate=0M;
if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["origrate"].Value.ToString()))
   iorigrate =Convert.ToDecimal(dataGridView1.Rows[i].Cells["origrate"].Value);


to:
decimal iorigrate=0M;
if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["origrate"].Value))
   iorigrate =Convert.ToDecimal(dataGridView1.Rows[i].Cells["origrate"].Value);


FYI, use Decimal.TryParse method instead, to prevent getting these kind of errors.

Here for your reference:
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx[^]

Regards,
Eduard
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

see this codes:


 foreach (GridViewRow gridviewrow in grvAuction.Rows)
{
                       
  decimal iorigrate=0M;
//Cells[1] - index of desired cell
 if(!string.IsNullOrEmpty(dataGridView1.Cells[1].Text))
  {
   iorigrate =Decimal.Parse(dataGridView1.Rows[i].Cells[1].Value);

   }
}

hope it helps!

thnks


don't forget to vote:)
   

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