user1722654
user1722654

Reputation: 59

error message fix

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    //bool sleected = false;

    if (dataGridView1.Rows[i].Cells[3].Value != null)
    {

        selected.Add(i);
    }

}
//string donew = "";


// line off error 
textBox1.Text = ((String)dataGridView1.Rows[1].Cells[2].Value);
/*  for (int i = 0; i < selected.Count; i++)
{

    textAdded.Add((String)dataGridView1.Rows[0].Cells[2].Value);
 //   donew += (String)dataGridView1.Rows[selected[i]].Cells[2].Value;
}*/

I keep getting the error

Unable to cast object of type 'System.Double' to type 'System.String'

What can I do to overcome this?

Upvotes: 0

Views: 108

Answers (3)

Ron Thacker
Ron Thacker

Reputation: 191

Additionally, you could further refine and clean it up with a foreach loop. This would make it easier to read in many cases.

Also, as a general practice avoid textBox1 or dataGridView1 type names for these objects. Specific naming schemas applied now, prevent needless grief and worry later. It's a good habit to get into as early as possible.

foreach(DataGridViewRow r in dataGridView1.Rows)
{
    if (r.Cells[3].Value != null)
    {
        selected.Add(r);
    }
}
// line off error 
textBox1.Text = dataGridView1.Rows[1].Cells[2].Value.ToString();

Upvotes: 1

Freeman
Freeman

Reputation: 5801

instead of using

textBox1.Text = ((String)dataGridView1.Rows[1].Cells[2].Value);

use

textBox1.Text = dataGridView1.Rows[1].Cells[2].Value.ToString();

The reason is that you where attempting an explicit cast whereas a cast from double to string does not exist, but fortunately the ToString() method outputs the number as a string.

Upvotes: 4

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with

dataGridView1.Rows[1].Cells[2].Value.ToString()

Upvotes: 0

Related Questions