2012-10-08 46 views
0
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; 
}*/ 

我不断收到错误错误信息修正

无法转换类型“System.Double”的对象为类型“System.String”

我能做些什么来克服这个?

回答

4

而是采用

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

使用

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

的原因是,你在哪里双重试图进行明确的转换而强制转换为字符串不存在,但幸运的ToString()方法以字符串形式输出数字。

0

您可以

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

尝试此外,可以进一步细化,并与foreach循环清理。这会使得在许多情况下更容易阅读。

此外,作为一般惯例,请避免textBox1dataGridView1这些对象的类型名称。现在应用特定的命名模式,以防止不必要的悲伤和后顾之忧。尽早进入是个好习惯。

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();