How to get columns from a datarow? - c#

I have a row collection (DataRow[] rows). And I want to import all rows to another DataTable (DataTable dt).
But how?
Code
DataTable dt;
if (drs.Length>0)
{
dt = new DataTable();
foreach (DataRow row in drs)
{
dt.Columns.Add(row???????)
}
// If it possible, something like that => dt.Columns.AddRange(????????)
for(int i = 0; i < drs.Length; i++)
{
dt.ImportRow(drs[i]);
}
}

Assuming the rows all have the same structure, the easiest option is to clone the old table, omitting the data:
DataTable dt = drs[0].Table.Clone();
Alternatively, something like:
foreach(DataColumn col in drs[0].Table.Columns)
{
dt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
}

If your DataRows is from a Data Table with Columns defined in it,
DataRow[] rows;
DataTable table = new DataTable();
var columns = rows[0].Table.Columns;
table.Columns.AddRange(columns.Cast<DataColumn>().ToArray());
foreach (var row in rows)
{
table.Rows.Add(row.ItemArray);
}

How about
DataTable dt = new DataTable;
foreach(DataRow dr in drs)
{
dt.ImportRow(dr);
}
Note this only works if drs is a DataRowCollection. Detached rows (not in a DataRowCollection are ignored).
Don't forget to call AcceptChanges.

Try this:
// Assuming you have a DataRow object named row:
foreach(DataColumn col in row.Table.Columns)
{
// Do whatever you need to with these columns
}

Related

Why conversion from Gridview to datatable fails?

I have been trying to convert GRIDVIEW to DataTable but it doesn't give me data, it only gives me HEADERS of GridView but not the data inside it. Why ? I am using template fields in gridview
Calling it from event:
DataTable dt = GetDataTable(GridView DenominationsWiseTransactions);
Conversion function:
DataTable GetDataTable(GridView dtg)
{
DataTable dt = new DataTable();
// add the columns to the datatable
if (dtg.HeaderRow != null)
{
for (int i = 0; i < dtg.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(dtg.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in dtg.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ", "");
}
dt.Rows.Add(dr);
}
return dt;
}
So, when you are looping through the rows in the datagrid, it will include headers, the rows and the footer.
To see just the data rows you need to do something like:
if (e.Row.RowType == DataControlRowType.DataRow)
{ //convert that row }
Your conversion line might need some work, but at least you'll only need to concern yourself with datarows now.

two datatable adding

I have two datatables.
1st table-----> DataTable _dtMain = new COrder().GetDetails();
2nd table-----> DataTable _dtSub = new CGrid().GetSubDetails();
I want to add the above two tables. I am using _dtMain.Merge(_dtSub );
But it will append _dtSub table to _dtMain table. I want datatable to add second table to first table in column wise (that means after first table last column)
Don't think there any built-in method for the thing you want to achieve.
I think you need to make your own implementation for that stuff, like for example an extension method
public static DataTable Aggregate(this DataTable dt1, DataTable dt2)
{
var aggregator = new DataTable();
//add columns from dt1 and dt2
//add rows from dt1 dt2
}
or, you can do a complete Outer Join on both tables, like descrived in this article.
After a lot of research , i find out the answer for my question that i posted before. Here is the code for combing 2 datatable & the data inside it.
public DataTable CombineTable(DataTable _dtGridDetails, DataTable _dtSubGridDetails)
{
//first create the datatable columns
DataSet mydataSet = new DataSet();
mydataSet.Tables.Add(" ");
DataTable myDataTable = mydataSet.Tables[0];
//add left table columns
DataColumn[] dcLeftTableColumns = new DataColumn[_dtGridDetails.Columns.Count];
_dtGridDetails.Columns.CopyTo(dcLeftTableColumns, 0);
foreach (DataColumn LeftTableColumn in dcLeftTableColumns)
{
if (!myDataTable.Columns.Contains(LeftTableColumn.ToString()))
myDataTable.Columns.Add(LeftTableColumn.ToString());
}
//now add right table columns
DataColumn[] dcRightTableColumns = new DataColumn[_dtSubGridDetails.Columns.Count];
_dtSubGridDetails.Columns.CopyTo(dcRightTableColumns, 0);
foreach (DataColumn RightTableColumn in dcRightTableColumns)
{
if (!myDataTable.Columns.Contains(RightTableColumn.ToString()))
{
// if (RightTableColumn.ToString() != RightPrimaryColumn)
myDataTable.Columns.Add(RightTableColumn.ToString());
}
}
//add left-table data to mytable
foreach (DataRow LeftTableDataRows in _dtGridDetails.Rows)
{
myDataTable.ImportRow(LeftTableDataRows);
}
for (int nIndex = 0; nIndex <= myDataTable.Rows.Count-1; nIndex++)
{
if (nIndex == _dtSubGridDetails.Rows.Count)
break;
myDataTable.Rows[nIndex][columnindex] = _dtSubGridDetails.Rows[nIndex][columnindex];
}
return myDataTable;
}

How to 'foreach' a column in a DataTable using C#?

How do I loop through each column in a datarow using foreach?
DataTable dtTable = new DataTable();
MySQLProcessor.DTTable(mysqlCommand, out dtTable);
foreach (DataRow dtRow in dtTable.Rows)
{
//foreach(DataColumn dc in dtRow)
}
This should work:
DataTable dtTable;
MySQLProcessor.DTTable(mysqlCommand, out dtTable);
// On all tables' rows
foreach (DataRow dtRow in dtTable.Rows)
{
// On all tables' columns
foreach(DataColumn dc in dtTable.Columns)
{
var field1 = dtRow[dc].ToString();
}
}
I believe this is what you want:
DataTable dtTable = new DataTable();
foreach (DataRow dtRow in dtTable.Rows)
{
foreach (DataColumn dc in dtRow.ItemArray)
{
}
}
You can do it like this:
DataTable dt = new DataTable("MyTable");
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
if (row[column] != null) // This will check the null values also (if you want to check).
{
// Do whatever you want.
}
}
}
You can check this out. Use foreach loop over a DataColumn provided with your DataTable.
foreach(DataColumn column in dtTable.Columns)
{
// do here whatever you want to...
}
Something like this:
DataTable dt = new DataTable();
// For each row, print the values of each column.
foreach(DataRow row in dt .Rows)
{
foreach(DataColumn column in dt .Columns)
{
Console.WriteLine(row[column]);
}
}
http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx
In LINQ you could do something like:
foreach (var data in from DataRow row in dataTable.Rows
from DataColumn col in dataTable.Columns
where
row[col] != null
select row[col])
{
// do something with data
}
int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;
for (int iCol = 0; iCol < countCol; iCol++)
{
DataColumn col = dt.Columns[iCol];
for (int iRow = 0; iRow < countRow; iRow++)
{
object cell = dt.Rows[iRow].ItemArray[iCol];
}
}

How to make a DataTable from DataGridView without any Datasource?

I want to get a DataTable from DataGridView of the Grid values.
In other words DataTable same as DataGridView Values
Might be a nicer way to do it but otherwise it would be fairly trivial to just loop through the DGV and create the DataTable manually.
Something like this might work:
DataTable dt = new DataTable();
foreach(DataGridViewColumn col in dgv.Columns)
{
dt.Columns.Add(col.Name);
}
foreach(DataGridViewRow row in dgv.Rows)
{
DataRow dRow = dt.NewRow();
foreach(DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
You can cast the DataSource object from the DataGridView to a DataTable
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
you can use the following code also, this code fill not effect on your DataGridView when you do some add or delete rows in the datatable
DataTable dt = new DataTable();
dt = Ctype(dataGridView1.DataSource,DataTable).copy();
You can try as follow:
using System.Data;
using System.Windows.Forms;
namespace BLL
{
public class Class_DataGridview_To_DataTable
{
public static DataTable UDF_Convert_DataGridView_To_Datatable(DataGridView ImpGrd)
{
DataTable ExportDataTable = new DataTable();
foreach (DataGridViewColumn col in ImpGrd.Columns)
{
ExportDataTable.Columns.Add(col.Name);
}
foreach (DataGridViewRow row in ImpGrd.Rows)
{
DataRow dRow = ExportDataTable.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
ExportDataTable.Rows.Add(dRow);
}
return ExportDataTable;
}
}
}

Simple way to convert datarow array to datatable

I want to convert a DataRow array into DataTable ... What is the simplest way to do this?
For .Net Framework 3.5+
DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();
But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.
if (dr.Length > 0)
DataTable dt1 = dr.CopyToDataTable();
Reference available at MSDN:
DataTableExtensions.CopyToDataTable Method (IEnumerable)
Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:
foreach (DataRow row in rowArray) {
dataTable.ImportRow(row);
}
Make sure your dataTable has the same schema as the DataRows in your DataRow array.
DataTable dt = new DataTable();
DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria");
dt.Rows.Add(dr);
Another way is to use a 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");
Simple way is:
// 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());
DataTable Assetdaterow =
(
from s in dtResourceTable.AsEnumerable()
where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
select s
).CopyToDataTable();
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();
DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{
dt.ImportRow(dr);
}
.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method
For datarow array just use .CopyToDataTable() and it will return datatable.
For single datarow use
new DataRow[] { myDataRow }.CopyToDataTable()
You could use System.Linq like this:
if (dataRows != null && dataRows.Length > 0)
{
dataTable = dataRows.AsEnumerable().CopyToDataTable();
}
Here is the solution. It should work fine.
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);
}
Incase anyone needs it in VB.NET:
Dim dataRow as DataRow
Dim yourNewDataTable as new datatable
For Each dataRow In yourArray
yourNewDataTable.ImportRow(dataRow)
Next
You need to clone the structure of Data table first then import rows using for loop
DataTable dataTable =dtExisting.Clone();
foreach (DataRow row in rowArray) {
dataTable.ImportRow(row);
}
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);
}

Categories