2010-12-09 25 views
0

在嘗試使用C#.net編碼將gridviewrow.cells值的值轉換爲int32時遇到問題。請考慮以下編碼。如何將gridviewrow.cells [i]值的值轉換爲int32?

DataTable dt = new DataTable(); 
dt.Columns.Add(new DataColumn("studentid",typeof(Int32))); 
dt.Columns.Add(new DataColumn("Name",typeof(string))); 
foreach (GridViewRow row in GridView1.Rows) 
{ 
    DataRow dr; 
    dr = dt.NewRow(); 
    CheckBox cb = (CheckBox)row.FindControl("Chkgridselect"); 
    if (cb.Checked) 
    { 
     //Error occurs in the following line when i try to typecast 
     dr["studentid"] =Convert.ToInt32(row.Cells[1]); 
     dr["Name"] = row.Cells[2]; 
     dt.Rows.Add(dr); 
    } 
} 
+1

請包括您的代碼並解釋它是如何失敗的。 – David 2010-12-09 14:02:36

+0

也許你沒有在一個單元格中獲得Int32! – 2010-12-09 14:05:26

+1

不應該轉換第一個單元格,索引爲0的單元格嗎?據我所知,你實際上將第二列轉換爲int。 – 2010-12-09 14:10:47

回答

1

添加一些代碼會有所幫助,但我要帶刺,說試試這個:

int myVal = Int32.Parse(GridViewRow.Cells[i].Text); 
1
int result; 

result = int.Parse(value); 

// OR 

result = Convert.Int32(value); 
2

只是在黑暗中刺沒有更多的信息。但請嘗試:

int myValue; 
if (!int.TryParse(myGridViewRow.Cells[i].Text, out myValue) 
//do something, your value is not an int 
0

DataGridViewCell具有Value屬性。

.... 
dr["studentid"] = Convert.ToInt32(row.Cells[1].Value); 
....