2012-09-28 39 views
25

Tengo un DataGridView vinculado a un DataTable (DataTable vinculado a la base de datos). Necesito agregar un DataRow al DataTable. Estoy tratando de utilizar el siguiente código:¿Cómo agregar un nuevo DataRow en DataTable?

dataGridViewPersons.BindingContext[table].EndCurrentEdit(); 
DataRow row = table.NewRow(); 

for (int i = 0; i < 28; i++) 
{ 
    row[i] = i.ToString(); 
} 

Pero no funciona, DataGridView nunca se ha añadido una nueva fila. Por favor, dime, ¿cómo puedo arreglar mi código?

Gracias de antemano.

+3

http://www.dotnetperls.com/datarow –

Respuesta

2

Tienes que add the row explícitamente a la mesa

table.Rows.Add(row); 
0

tratar table.Rows.add(row); después de su declaración for.

1

Esto funciona para mí:

var table = new DataTable(); 
table.Rows.Add(); 
3

Si necesidad de copiar de otra tabla a continuación, tiene que copiar primera estructura:

DataTable copyDt = existentDt.Clone(); 
copyDt.ImportRow(existentDt.Rows[0]); 
8

// Creación de una nueva fila con la estructura de la tabla:

DataTable table = new DataTable(); 
DataRow row = table.NewRow(); 
table.Rows.Add(row); 

// dando valores a las columnas de la fila (esta fila se supone que tiene 28 columnas):

for (int i = 0; i < 28; i++) 
{ 
    row[i] = i.ToString(); 
} 
4

Encontré dotnetperls examples on DataRow muy útil. Fragmento de código para la nueva DataTable desde allí:

static DataTable GetTable() 
{ 
    // Here we create a DataTable with four columns. 
    DataTable table = new DataTable(); 
    table.Columns.Add("Weight", typeof(int)); 
    table.Columns.Add("Name", typeof(string)); 
    table.Columns.Add("Breed", typeof(string)); 
    table.Columns.Add("Date", typeof(DateTime)); 

    // Here we add five DataRows. 
    table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now); 
    table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now); 
    table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now); 
    table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now); 
    table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now); 

    return table; 
} 
0
GRV.DataSource = Class1.DataTable; 
      GRV.DataBind(); 

Class1.GRV.Rows[e.RowIndex].Delete(); 
     GRV.DataSource = Class1.DataTable; 
     GRV.DataBind(); 
+4

Por favor, intente evitar simplemente vertido código como una respuesta y tratar de explicar lo que hace y por qué. Es posible que su código no sea obvio para las personas que no tienen la experiencia de codificación relevante. Edite su respuesta para incluir [aclaraciones, contexto e intente mencionar cualquier limitación, suposición o simplificación en su respuesta]. (Https://stackoverflow.com/help/how-to-answer) –

Cuestiones relacionadas