Hey there

I have a part in my program where it should calculate the total in one column of my datagridview. All goes well and good while there are no Null values between them in my column. So i thought ill use exception handling seeing that my If statement throws me more errors than I can handle.

(Just to show you what i did with my if statement, (but it said "Object cannot be cast from DBNull to other types.")

for (counter = 0; counter < (tblAllEntries.Rows.Count); counter++)
            {
                if (tblAllEntries.Rows[counter].Cells[2].Value.ToString() == null)
                {
                    TotalExpense += 0;
                }
                else
                {
                    TotalExpense += Convert.ToInt32(tblAllEntries.Rows[counter].Cells[2].Value);
                }
            }

Oky so that didnt work, and i have no idea how to Get it to work?

So i thought id do it with exception handling. So this is how it looked

try
         {
            for (counter = 0; counter < (tblAllEntries.Rows.Count); counter++)
            {
  
             TotalExpense += Convert.ToInt32(tblAllEntries.Rows[counter].Cells[2].Value);
                }
            }
         }

            catch (InvalidCastException a)
            {
                TotalExpense += 0;
             }

But now it counts till it reaches a blank spot. How do i make it continue counting after it has cached that exception?

Thank you..
Ruan

Recommended Answers

All 2 Replies

You can change the order of try and for.

for (counter = 0; counter < (tblAllEntries.Rows.Count); counter++)
      {
		try {
			TotalExpense += Convert.ToInt32(tblAllEntries.Rows[counter].Cells[2].Value);
		}
		catch (InvalidCastException a)
		{
			TotalExpense += 0;
		}
      }

You can change the order of try and for.

for (counter = 0; counter < (tblAllEntries.Rows.Count); counter++)
      {
		try {
			TotalExpense += Convert.ToInt32(tblAllEntries.Rows[counter].Cells[2].Value);
		}
		catch (InvalidCastException a)
		{
			TotalExpense += 0;
		}
      }

ahhhhh of coarse! Brilliant, Works Perfectly

Thank you dgirdhar!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.