2017-03-01 6 views
1

텍스트 파일에 쓰려는 DataGridview가 있습니다. 여기 내 코드입니다 :DataGridView에서 Windows Forms의 텍스트 파일로 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

조,

당신의 루프 각의를 사용해보십시오 :

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

그리드에있는 하나 이상의 값이 null이거나 다른 말로하면 '아무것도'가 아닙니다. 따라서 dataGridView.Rows[i].Cells[col].Value 속성에 액세스하여 문자열로 변환하면 null을 문자열로 변환하여 예외를 throw하려고합니다. (당신이 .NET 4.6 사용하는 경우) 당신이 사용하는 경우 (Value

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

통지에게 여분의 물음표를

: 당신은 null 값이 같은 것을 확인해야 이전 .net)

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

희망이 도움이됩니다.

편집 : System.ArgumentOutOfRangeException이되었으므로 많은 수의 행이나 열을 액세스하려고 할 때 그리드의 경계를 벗어나지 않도록하십시오. 당신이 바인딩에있어 반드시 두 번째

+0

코드를 시도 할 때이 코드가 나타납니다 'System.ArgumentOutOfRangeException'유형의 처리되지 않은 예외가 발생했습니다 –

+0

@ Joe.guid 내 대답을 편집했습니다 ... – Nino

+0

당신은 진정한 생명의 보호기입니다! –

관련 문제