2010-01-23 47 views

Respuesta

70

Por qué no iterar a través de la matriz de DataRow y añadir (utilizando DataRow.ImportRow, si es necesario, para obtener una copia de la DataRow), algo así como:

foreach (DataRow row in rowArray) { 
    dataTable.ImportRow(row); 
} 

Asegúrese de que tiene el dataTable mismo esquema que las DataRows en su matriz DataRow.

+0

Esta técnica es útil si aparece el mensaje de error "Se está utilizando una fuente de datos no válida para MyControl. Una fuente de datos válida debe implementar IListSource o IEnumerable" al intentar enlazar una DataRow directamente a la propiedad DataSource de un control. Aquí le mostramos cómo hacerlo: 'DataTable dataTable = new DataTable(); dataTable.ImportRow (dataRow); MyControl.DataSource = dataTable; ' – humbads

+0

+1 Prefiero esto en lugar de' rowArray.CopyToDataTable(); 'porque esto mantiene el esquema de la tabla y no lo reemplaza con un nuevo objeto de tabla. –

+1

¡Muy bien! Pero yo recomendaría clonar DataTable antes de foreach. Copia el formato de DataTable: newDataTable = oldDataTable.clone(); – Whiplash

10
DataTable dt = new DataTable(); 

DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria"); 

dt.Rows.Add(dr); 
+2

ya me trataron como esa .. El error se produce algo así como "matriz de entrada es más larga que el número de columnas en esta tabla ". – Nila

+0

Como Jay señaló, asegúrese de que su dataTable tenga el mismo esquema que las DataRows en su matriz DataRow –

+1

Sí ... Lo intenté. Utilicé Datatable1 = datatable2.Clone(); Ahora está funcionando ... Gracias :-) – Nila

163

Para .Net Framework 3.5+

DataTable dt = new DataTable(); 
DataRow[] dr = dt.Select("Your string"); 
DataTable dt1 = dr.CopyToDataTable(); 

Pero si no hay filas de la matriz, puede hacer que los errores como La fuente no contiene DataRows. Por lo tanto, si decide utilizar este método CopyToDataTable(), debe verificar la matriz para saber si tiene datarows o no.

if (dr.Length > 0) 
    DataTable dt1 = dr.CopyToDataTable(); 

de referencia disponible en MSDN: DataTableExtensions.CopyToDataTable Method (IEnumerable)

+0

Me gusta este. –

+1

¿De dónde obtienes 'copyToDataTable()'? No lo encontré en .net 2.0 – SMUsamaShah

+1

.NET Framework 3.5+ –

2

Aquí está la solución. Debería funcionar bien.

DataTable dt = new DataTable(); 
dt = dsData.Tables[0].Clone(); 
DataRows[] drResults = dsData.Tables[0].Select("ColName = 'criteria'); 

foreach(DataRow dr in drResults) 
{ 
    object[] row = dr.ItemArray; 
    dt.Rows.Add(row); 
} 
9

Otra forma es utilizar un DataView

// Create a DataTable 
DataTable table = new DataTable() 
... 

// Filter and Sort expressions 
string expression = "[Birth Year] >= 1983"; 
string sortOrder = "[Birth Year] ASC"; 

// Create a DataView using the table as its source and the filter and sort expressions 
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows); 

// Convert the DataView to a DataTable 
DataTable new_table = dv.ToTable("NewTableName"); 
3
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>(); 
3
DataTable dt = new DataTable(); 
foreach (DataRow dr in drResults) 
{ 
    dt.ImportRow(dr); 
} 
5

Una manera sencilla es:

// dtData is DataTable that contain data 
DataTable dt = dtData.Select("Condition=1").CopyToDataTable(); 

// or existing typed DataTable dt 
dt.Merge(dtData.Select("Condition=1").CopyToDataTable()); 
1

En caso que alguien lo necesita en VB.NET:

Dim dataRow as DataRow 
Dim yourNewDataTable as new datatable 
For Each dataRow In yourArray 
    yourNewDataTable.ImportRow(dataRow) 
Next 
1

.Net 3.5+ añadió DataTableExtensions, utilice DataTableExtensions.CopyToDataTable Método

Para DataRow array sólo tiene que utilizar .CopyToDataTable() y volverá tabla de datos.

Para un solo uso DataRow

new DataRow[] { myDataRow }.CopyToDataTable() 
0

Usted podría utilizar System.Linq así:

if (dataRows != null && dataRows.Length > 0) 
{ 
    dataTable = dataRows.AsEnumerable().CopyToDataTable(); 
} 
0
DataTable dataTable = new DataTable(); 
dataTable = OldDataTable.Tables[0].Clone(); 
foreach(DataRow dr in RowData.Tables[0].Rows) 
{ 
DataRow AddNewRow = dataTable.AddNewRow(); 
AddNewRow.ItemArray = dr.ItemArray; 
dataTable.Rows.Add(AddNewRow); 
} 
+1

Please agregue alguna explicación del código provisto –