2014-01-22 48 views
0

我想检索所有数字(因为列中还有其他内容像“N/A”等)在我的列中DataGridView并将它们写入List<int>从DataGridView的列中提取所有数字,并写入一个int列表

一些伪代码:

List<int> data = new List<int>(); 
foreach (string s from column 3 in DataGridView) 
{ 
    Check if s can be converted into a number; 
    data.Add(Convert.ToInt32(s)); 
} 
+1

您可以使用'Int32.TryParse'而不是'Convert.ToInt32'。 –

回答

3
foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
     int result; 
     if(int.TryParse((string)row.Cells[2].Value,out result)) data.Add(result); 
    } 
+0

这会触发'System.InvalidCastException',System.Int32不能转换为类型System.String – jacobz

+0

写'row.Cells [2] .Value.ToString()'而不是'(字符串)row.Cells [2] .Value ' – prograshid

+0

@雅各布斯21在哪里? –

1

循环遍历行,并获得特定列的值。使用int.TryParse尝试将值解析为int。如果失败,你的循环将继续。

foreach(var item in DataGridView.Rows) 
{ 
    int value; 
    if(int.TryParse(item.Cells[2].Value.ToString(), out value)) //Cells[2] is column #3 
    { 
     data.Add(value); 
    } 
} 
0

遍历的DataGridView行和获得所需的列的值。

foreach(var row in DataGridView.Rows) 
{ 
    int value; 
    if(int.TryParse(rows.Cells[2].Value.ToString(), out value)) 
    { 
    yourList.Add(value); 
    } 
} 
+0

这样做时我得到一个System.NullReferenceException。是因为我将它包装在BeginInvoke((MethodInvoker)委托{}中,因为它在BackgroundWorker中运行? – jacobz

相关问题