2010-04-05 4 views
7

나는 datagridview의 모든 행을 반복하고 셀에서 값을 가져 오는 가장 좋은 방법은 무엇인지 궁금합니다.
다음은 내가 생각하고있는 것입니다. 그러나 열을 재정렬하면 코드도 변경되어야하기 때문에 정말 좋아하지 않습니다.DataGridView의 경우 각 행에서 값을 얻으려면 어떻게해야합니까?

for (int i = 0; i < dataGridView.RowCount; i++) 
{ 
    string Value0 = dataGridView1.Rows[i].Cells[0]; 
    string Value1 = dataGridView1.Rows[i].Cells[1]; 
    string Value2 = dataGridView1.Rows[i].Cells[2]; 
} 
당신은 DataGridViewDataGridViewRow의 반복하는 foreach를 사용에서 값을 검색하려면 열 이름을 사용할 수

답변

11

Cells :

foreach (DataGridViewRow dr in dataGridView.Rows) 
{ 
    string col1 = dr.Cells["Col1"].Value.ToString(); 
    string col2 = dr.Cells["Col2"].Value.ToString(); 
    string col3 = dr.Cells["Col3"].Value.ToString(); 
} 
+1

고맙습니다. Dr.Cells [ "Col1"] .ToString() "에서"dr1Cells [ "Col1"]까지의 작은 변경. Value.ToString() " – skid

+0

그것은 당신에게 효과적이라고 다행입니다. 이 답변을 찾은 다른 사용자를 위해 'Value'를 추가하기 위해 내 대답을 수정했습니다. – CAbbott

+0

Ninja'd, 셀에 올바른 데이터를 가져 오기 위해 Value가 필요하다는 것을 추가하려고했습니다. – Justin

1

NullException은 당신이 할 수있는이 오류를 방지하기 위해 발생할 수 있습니다 위 코드를 다음과 같이 수정하십시오.

foreach (DataGridViewRow dr in dataGridView1.Rows) 
{ 
    //variables with looop through 
    string col1 = Convert.ToString(dr.Cells["col1"].Value); 
    string col2 = Convert.ToString(dr.Cells["col2"].Value); 
    string col3 = Convert.ToString(dr.Cells["col3"].Value); 
} 
관련 문제