2017-03-01 18 views
1

テキストファイルに書きたいデータグリッドビューがあります。ここに私のコードは次のとおりです。DataGridViewからWindowsフォームのテキストファイルへC#

private void WriteToFile_Click(object sender, EventArgs e) 
{ 
    StreamWriter sW = new StreamWriter("list.txt"); 
    for (int i = 0; i < 6; i++) 
    { 
     string lines = ""; 
     for (int col = 0; col < 6; col++) 
     { 
      lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + 
       dataGridView.Rows[i].Cells[col].Value.ToString(); 
     } 
     sW.WriteLine(lines); 
     sW.Close(); 
    } 
} 

と私はそれは私にエラーを与えるボタンをクリックしてください:

System.NullReferenceException

+0

こんにちはジョーのためにあなたの最初のループの

for (int i = 0; i < dataGridView.RowCount; i++) 

for (int col = 0; col < dataGridView.ColumnCount; col++) 

を使用するには、あなたの質問にもう少し力を入れてみてください。たとえば、WriteToFile_Clickを使用してデバッグすると、null参照が返されますか? このような詳細はお手伝いします。 – Alex

+0

あなたのグリッドが6x6より小さいかどうかを確認してください – wdc

+0

ああ、ごめんなさい、+ =(string.IsNullOrEmpty(lines)? "": "、")+ dataGridView.Rows [i] .Cells [ col] .Value.ToString(); –

答えて

1

ジョー、

は、あなたのforループごとに使用してみてください:

StreamWriter sW = new StreamWriter("list.txt"); 
foreach (DataGridViewRow r in dataGridView.Rows) { 
    string lines = ""; 
    foreach (DataGridViewCell c in r.Cells) { 
     lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value; 
    } 

    sW.WriteLine(lines); 
} 
+0

確かに良く見えますが、ToString()を実行する前にc.Valueでnullをチェックする必要があります。そうしないと、NullReferenceExceptionが発生します。 –

1

グリッド内の1つ以上の値がnullであるか、言い換えれば「何もありません」となります。したがって、dataGridView.Rows[i].Cells[col].Valueプロパティにアクセスして文字列に変換すると、nullを文字列に変換して例外をスローします。 あなたは、null値のために、このような何かを確認する必要があります:

(あなたは.NET 4.6を使用している場合)

lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value?.ToString(); 

を予告余分な疑問符Value

後(あなたが使用している場合より古い.net)

lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value; 

これは役立ちます。

EDIT: あなたはSystem.ArgumentOutOfRangeExceptionになっているので、グリッドの境界から外れていないことを確認してください。多くの行や列にアクセスしようとしています。 、あなたがバウンドにいることを確認し二

+0

コードを試してみるとこれが表示されます 'System.ArgumentOutOfRangeException'型の未処理の例外が発生しました –

+0

@ Joe.guid私の回答を編集しました... – Nino

+0

あなたは本当の人生の節約になりました。 –

関連する問題