2011-05-23 16 views
10

estoy tratando de ejecutar este código, y me sale una excepción:¿Cómo puedo agregar datos manualmente a un dataGridView?

índice estaba fuera del rango. Debe ser no negativo y menor que el tamaño de la colección. Nombre de parámetro: índice de

private void LoadStudentGrades(int gradeParaleloId, int subjectId) 
{ 
    GradeStudentRepository gradeStudentRepo = new GradeStudentRepository(); 
    students = gradeStudentRepo.FindAllGradeStudents().Where(g => g.GradeParaleloId == gradeParaleloId) 
       .Select(g => g.Student); 

    int i = 1; 
    foreach (var student in students) 
    { 
     DataGridViewRow row = new DataGridViewRow(); 

     row.Cells[0].Value = i.ToString(); 
     row.Cells[1].Value = student.LastNameFather + " " + student.LastNameMother + ", " + student.Name; 

     dataGridView1.Rows.Add(row); 
     i++; 
    } 
} 

que crear manualmente las columnas en el DataGridView, y ahora me gustaría para rellenar los campos que utilizan este pequeño método.

+1

¿Estás seguro de que hay columnas disponibles para 'datagridview1'? – V4Vendetta

+1

¿Qué quieres decir con "¿Creé manualmente las columnas en la vista de cuadrícula de datos"? ¿Quiere decir que definió columnas en la hoja de propiedades "Columnas" de la instancia de DataGridView colocada en un formulario, o quiere decir que definió columnas utilizando el código C# en otro lugar? – barrypicker

Respuesta

2

Hay 0 celdas en la fila recién creada, es por eso que está obteniendo esa excepción. No puede usar sentencias como

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

a menos que agregue celdas manualmente a la fila en blanco.

1

Versión sencilla:

dataGridView1.Rows.Add(new object[] { cell0Value, cell1Value }); 

Mi extensión que me gusta usar:

static class DataGridViewExtension 
{ 
    public static void AddCustomRow(this DataGridView dgv, object [] values, object tag = null) 
    { 
     int Index = dgv.Rows.Add(values); 

     // Add a tag if one has been specified 
     if (tag != null) 
     { 
      DataGridViewRow row = dgv.Rows[Index]; 
      row.Tag = tag; 
     } 
    } 

    public static void AddCustomRow(this DataGridView dgv, string text, object tag = null) 
    { 
     AddCustomRow(dgv, new object[] { text }, tag); 
    } 
} 
7

Su simple,

myDataGridView.Rows.Add(value1, value2, value3...); 

Funcionó cuando había configurado mi DGV previamente para el próximas columnas de datos a través de la GUI. Así, en su caso, que sería como:

private void LoadStudentGrades(int gradeParaleloId, int subjectId) 
{ 
    GradeStudentRepository gradeStudentRepo = new GradeStudentRepository(); 
    students = gradeStudentRepo.FindAllGradeStudents().Where(g => g.GradeParaleloId == gradeParaleloId).Select(g => g.Student); 

    int i = 1; 
    foreach (var student in students) 
    { 
     dataGridView1.Rows.Add(i.ToString(), student.LastNameFather + " " + student.LastNameMother + ", " + student.Name); 
     i++; 
    } 
} 

Puede ser que usted tiene que configurar el DGV para las columnas y sus nombres por separado.

25

usted es apenas falta una línea :-P

DataGridViewRow row = new DataGridViewRow(); 
row.CreateCells(dataGridView1); // this line was missing 
row.Cells[0].Value = "Cell1"; 
row.Cells[1].Value = "Cell2"; 
dataGridView1.Rows.Add(row); 
+1

+1 para CreateCells Siempre olvido que –

+1

Esta respuesta se basa en que el programador tiene columnas definidas en la instancia de DataGridView en un formulario (llamado 'dataGridView1'). La llamada al método CreateCells se basa en esta definición para configurar las columnas de la nueva fila. Para las personas que buscan una forma totalmente programática de definir un DataGridView, primero debe definir las columnas. Ver SO @ http://stackoverflow.com/questions/5524075/programatically-add-new-column-to-datagridview – barrypicker

2

Mi versión de este:

   OracleCommand cmd = new OracleCommand(commandText, _oraConn); 
       OracleDataReader dr = cmd.ExecuteReader(); 

       int i = 0; 
       while (dr.Read()) 
       { 
        DataGridViewRow row = new DataGridViewRow(); 
        row.CreateCells(dataGridView1); 


        row.Cells[0].Value = dr.GetValue(0).ToString(); 
        row.Cells[1].Value = dr.GetValue(1).ToString(); 
        row.Cells[2].Value = dr.GetValue(2).ToString(); 
        row.Cells[3].Value = dr.GetValue(3).ToString(); 
        row.Cells[4].Value = dr.GetValue(4).ToString(); 
        row.Cells[5].Value = dr.GetValue(5).ToString(); 

        dataGridView1.Rows.Add(row); 

        //MessageBox.Show(dr.GetValue("vz_id").ToString()); 
        i++; 
       }; 

Gracias por sus respuestas.

Cuestiones relacionadas