Click here to Skip to main content
15,897,032 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hai;


I work windows application using C#
my problem is "InvalidCastException was unhandled"
"Object cannot be cast from DBNull to other types."

in my application ,i have a datagridview control and a textbox.
and also i create a table named as Mark, in this table have 4 fields. they are name,mark,mark1,total.

1)Firstly i bind the data in the datagridview. my code is bellow


C#
private void Form4_Load(object sender, EventArgs e)
       {
           SqlDataAdapter da = new SqlDataAdapter("select * from  addr", con);
           DataSet ds = new DataSet();
           da.Fill(ds);
           dataGridView1.DataSource = ds.Tables[0];
       }

2) i do add mark and mark1 and store in total column in datagridview. my code is given bellow


C#
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
       {
           c1 = Convert.ToDouble(dataGridView1.CurrentRow.Cells[3].Value);
           a = Convert.ToDouble(dataGridView1.CurrentRow.Cells[1].Value);
           b = Convert.ToDouble(dataGridView1.CurrentRow.Cells[2].Value);
           dataGridView1.CurrentRow.Cells[3].Value = a * b;
           dataGridView1.Columns["Amount"].ReadOnly = true;

           c = 0;
           c = Convert.ToDouble(dataGridView1.CurrentRow.Cells[3].Value) - c1;
           ng = ng + Convert.ToDouble(c);
           c = 0;
           a = 0;
           textBox1.Text = ng.ToString();

       }


the error occured at this line "c1 = Convert.ToDouble(dataGridView1.CurrentRow.Cells[3].Value);"//InvalidCastException was unhandled " this is the error message.

how to over come these problem and how to edit/ add a new value inthis datagrideview.


please help me

thanks in advance.
Posted
Updated 21-Mar-12 8:45am
v2

You can use the Double.TryParse. This way you can check if there is a problem:

Double x;
if (Double.TryParse(dataGridView1.CurrentRow.Cells[3].Value, out x)
  c1 = x;
else
{
  //Whatever the fallback will be.
}
 
Share this answer
 
It simply means that the type of that Cell[3] content is not double. Just check it up. If it's the string, you can further parse if to double using double.Parse(string) or double.TryParse(string), but it would be a bad code design. You should better have right types in right cells, and, ultimately, right types in the columns of your database.

By the way, you are using hard coded immediate constants for the cell indices; this is always bad, hard to maintain, error-prone.

—SA
 
Share this answer
 
v2

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