2016-05-24 3 views
-3

こんにちは私はCellからデータを抽出する方法を研究しています。これは動作しますが、空のセルに達するたびにNullBinderExceptionが得られます。ループ中断のためにCellが空であることを確認してください。

私の質問はどうすればこの問題を防ぐことができますか?ここで

は問題を作る部分である:私が試した

while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null) 
    { 
     for (int i = 1; i <= numberOfColumns; i++) 
     { 
      string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString(); 
      stringList.Add(sValue); 
      cell++; 
     } 
     startpoint++; 
     cell = 1; 
    } 

スタッフ:これはaviableメンバーではありませんbecouse

range.Offset =カントは、使用しています。
IsNullOrEmpty =差はありません

だから私には得られないことがあります。どんな助けや助言も素晴らしいことでしょう、あなたの時間に感謝します。

+0

セルが空の場合、 'Value2'は' null'なのでなります。 'ToString'を安全に呼び出すことはできません。代わりに '... Value2!= null'をチェックしてください。 –

+0

[NullReferenceExceptionとは何か、それを修正する方法は?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)の可能な複製) –

+0

あなたの 'nullBinderException'を[try-catch(Referencia de C#)](https://msdn.microsoft.com/es-es/library/0yd65esw.aspx)することができます。 –

答えて

1

。 Where節でこれらを確認してください。

while ((range.Cells[startpoint, cell] as Excel.Range) != null && (range.Cells[startpoint, cell] as Excel.Range).Value2 != null) 
{ 
    for (int i = 1; i <= numberOfColumns; i++) 
    { 
     string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString(); 
     stringList.Add(sValue); 
     cell++; 
    } 
    startpoint++; 
    cell = 1; 
} 
1

あなたはあなたのようwhileループを作ることができます: - セル範囲および/または値2がnullの場合も

while (! IsNull(range.Cells[startpoint, cell] as Excel.Range).Value2)) 
0

あなたはあなたのような例外をキャッチしてみてください:

try 
{ 
    while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null) 
    { 
    for (int i = 1; i <= numberOfColumns; i++) 
    { 
     string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString(); 
     stringList.Add(sValue); 
     cell++; 
    } 
    startpoint++; 
    cell = 1; 
    } 
} 
catch(nullBinderException e) 
{ 
    //you find an empty cell 
    //... break? jump over and continue? 
    //... your logic... 
} 
関連する問題