2011-06-27 30 views

Respuesta

36

algo como

for (int rows = 0; rows < dataGrid.Rows.Count; rows++) 
{ 
    for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++) 
    { 
     string value = dataGrid.Rows[rows].Cells[col].Value.ToString(); 

    } 
} 

ejemplo sin utilizar índice

foreach (DataGridViewRow row in dataGrid.Rows) 
{ 
    foreach (DataGridViewCell cell in row.Cells) 
    { 
     string value = cell.Value.ToString(); 

    } 
} 
+5

En lugar de escribir el tipo de fila o celda, es decir, "DataGridViewRow" o "DataGridViewCell" respectivamente, simplemente puede escribir "var". –

+1

@kami si se usa var, row.Cells arroja un error porque cree que row es type object – Ravvy

0

Ejemplo Código: lectura de datos desde DataGridView y su almacenamiento en una matriz

int[,] n = new int[3, 19]; 
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++) 
{ 
    for (int j = 0; j < StartDataView.Columns.Count; j++) 
    { 
     if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty) 
     { 
      try 
      { 
       n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString()); 
      } 
      catch (Exception Ee) 
      { //get exception of "null" 
       MessageBox.Show(Ee.ToString()); 
      } 
     } 
    } 
} 
+0

No entiendo el try-catch en su ejemplo. Debe probar para asegurarse de que la celda no sea nula antes de analizarla. – carlbenson

+0

@Carl Benson - Gracias, he actualizado mi respuesta. – Bibhu

2
string[,] myGridData = new string[dataGridView1.Rows.Count,3]; 

int i = 0; 

foreach(DataRow row in dataGridView1.Rows) 

{ 

    myGridData[i][0] = row.Cells[0].Value.ToString(); 
    myGridData[i][1] = row.Cells[1].Value.ToString(); 
    myGridData[i][2] = row.Cells[2].Value.ToString(); 

    i++; 
} 

Espero que esto ayude ....

7

Si lo desea, también puede utilizar los nombres de columna en lugar de números de columna.

Por ejemplo, si desea leer datos de DataGridView en el 4. fila y la columna "Nombre". Me proporciona una mejor comprensión de la variable con la que estoy tratando.

dataGridView.Rows[4].Cells["Name"].Value.ToString(); 

Espero que ayude.

0
private void HighLightGridRows() 
     {    
      Debugger.Launch(); 
      for (int i = 0; i < dtgvAppSettings.Rows.Count; i++) 
      { 
       String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString(); 
       if (key.ToLower().Contains("applicationpath") == true) 
       { 
        dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; 
       } 
      } 
     }