2017-05-06 11 views
0

저는 프로그래밍에 비교적 익숙하지 않으므로 쉽게 할 수 있습니다!데이터 격자 반복 오류입니다. Exit For 루프 때 null입니까?

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll 

Additional information: Index was out of range. Must be non-negative and less than the size of the collection. 

어떻게 Dataagridview를 반복 처리 한 후에 이러한 오류가 발생하지 않도록 할 수 있습니까? 코드는 정확히 필요한 것을 수행합니다. for 루프는 모든 행을 반복했지만 행이 남아 있지 않으면 예외를 throw합니다. 모든 행이 변환되면 어떻게 나갈 수 있습니까?

foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 


      for (int i = 0; i < dataGridView1.Columns.Count; i++) 
      { 
       //String header = gridview_id.Columns[i].HeaderText; 
       // String cellText = row.Cells[i].Text; 

       partData.partID = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value); 
       partData.productName = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value); 
       partData.partDescription = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value); 
       partData.unitPrice = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value); 
       partData.quantity = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value); 
       partData.partNote = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value); 

       MessageBox.Show(PerformRequestUpdatePriority("http://dmcalla04.students.qub.ac.uk/import.php?", username, partData.partID, partData.productName, partData.partDescription, partData.unitPrice, partData.quantity, partData.partNote)); 
       Console.WriteLine(username); 


      } 
     } 

많은 분들께 미리 감사드립니다.

답변

0

그래서 기본적으로 당신은 dataGridView1.Rows[i] 라인에 액세스하려고하기 때문에 행의 수는 당신이받는 열 수보다 적은 것을 대신이 인수 예외에서 얻고있는 이유는 경우에 dataGridView1.Rows[i]row 변수를 사용할 필요가 존재하지 않는 배열의 인덱스.

foreach (var row in dataGridView1.Rows) 
{ 
    partData.partID = Convert.ToString(row.Cells[0].Value); 
    partData.productName = Convert.ToString(row.Cells[1].Value); 
    partData.partDescription = Convert.ToString(row.Cells[2].Value); 
    partData.unitPrice = Convert.ToString(row.Cells[3].Value); 
    partData.quantity = Convert.ToString(row.Cells[4].Value); 
    partData.partNote = Convert.ToString(row.Cells[5].Value); 

    MessageBox.Show(PerformRequestUpdatePriority("http://dcosgrove04.students.cs.qub.ac.uk/importParts.php?", username, partData.partID, partData.productName, partData.partDescription, partData.unitPrice, partData.quantity, partData.partNote)); 
    Console.WriteLine(username); 
} 

또는 싶어 사용 지수, 당신은 다음과 같은 코드를 사용할 수있는 경우 :

for (int rowIndex = 0; rowIndex < dataGrid.Rows.Count; rowIndex++) 
{ 
    var row = dataGridView1.Rows[rowIndex]; 
    partData.partID = Convert.ToString(row.Cells[0].Value); 
    partData.productName = Convert.ToString(row.Cells[1].Value); 
    partData.partDescription = Convert.ToString(row.Cells[2].Value); 
    partData.unitPrice = Convert.ToString(row.Cells[3].Value); 
    partData.quantity = Convert.ToString(row.Cells[4].Value); 
    partData.partNote = Convert.ToString(row.Cells[5].Value); 

    MessageBox.Show(PerformRequestUpdatePriority("http://dcosgrove04.students.cs.qub.ac.uk/importParts.php?", username, partData.partID, partData.productName, partData.partDescription, partData.unitPrice, partData.quantity, partData.partNote)); 
    Console.WriteLine(username); 
} 

을 당신 수도 또한 싶어 체크 this answer

+0

안녕하세요. 도움을 주셔서 감사합니다. 하지만 이건 행렬 때문에 작동하지 않습니다. 셀 []. 그것은 밑줄이 그어져 있습니다. '객체에는 세포에 대한 정의가 없습니다 ......'등 어떤 다른 제안입니까? –

+0

@DeanCosgrove [이 링크] (https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.cells (v = vs.110) .aspx)를 기반으로하고 또한 코드' DataGridViewRow'는'Cells'라는 속성을 가지고 있습니다. 대소 문자가 정확하다는 것을 확인할 수 있습니까? 당신이 셀 번호를 하드 코드 했으므로 두 번째 루프가 필요 없기 때문에 코드를 업데이트했습니다. – manman

+0

그래도 여전히 작동하지 않는 것을 확인할 수 있습니다. (이 속성을 사용하여이 속성을 호출 할 수 없습니다. 도움 사람을 보내 주셔서 감사합니다. –

0

딘, 당신이 행 또는 열을 참조하려고 DataGridView가 존재하지 않으면 '범위를 벗어남'오류가 발생합니다. 귀하의 경우에는, 당신의 카운터 (i)는 의 수에 대해 반복, 아직 코드는 DGV의 을 참조한다. 오류를 수정하면 문제가 해결됩니다. 귀하의 코멘트에 대한 응답으로

는 : 은 라인 교체 : 당신이 달성하기 위해 노력하고 정확히 알지 못하고 오류를 방지해야

for (int i = 0; i < dataGridView1.Rows.Count; i++) 

for (int i = 0; i < dataGridView1.Columns.Count; i++) 

을하지만, 그건 너를 훨씬 더 인도하기가 어렵다. 당신은 거기에 중첩 된 루프를 가지고 있으며, 볼 수있는 것에서는 중복되는 부분이 많이 있습니다.

+0

고맙다, 나는 무엇이 좋은지에 관해 안다. 오류와 관련하여 일어나고 있습니다. 코딩하지 않으면 발생하지 않습니다. 어떤 생각입니까?학장 –

+0

귀하의 질문에 대한 답변으로 답변을 업데이트했습니다. –

+0

안녕하세요 짐, 업데이트 된 댓글에 루프가 동일하게 표시 되나요? 중복 루프를 꺼 냈습니다. :) 오류가 발생하는 것을 방지하기 위해 데이터 격자 행을 반복 할 때 for 루프가 중단되거나 중지되도록하고 싶습니다. 예 : 모든 3 개의 행에 데이터가 추출되었을 때. 중지. 도와 주셔서 감사합니다 –