How to 'foreach' a column in a DataTable using C#? - 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];
}
}

Related

Adding a rank column to a data table after sorting it

i am trying to add a new column to a data table that is the rank. For that I want to loop through each row after sorting and then assign a rank to each row starting at 1.
Below is my code. However The rank is getting assigned to the row before the sort it looks like.
So my rank calculation is not doing what its supposed to do. Is it possible to add a rank this way?
protected void bindGridView(GridView gv)
{
using(DataTable dt = getData())
{
DataColumn dc_Total = new DataColumn("Total");
DataColumn dc_Rank = new DataColumn("Rank");
dt.Columns.Add(dc_Total);
dt.Columns.Add(dc_Rank);
dc_Rank.SetOrdinal(1);
dc_Total.SetOrdinal(2);
foreach (DataRow dr in dt.Rows)
{
dr["Total"] = Convert.ToDouble(dr["A_B_PERC"].ToString()) + Convert.ToDouble(dr["C_PERC"].ToString());
}
dt.DefaultView.Sort = "Total";
int rank = 1;
foreach(DataRow dr in dt.Rows)
{
dr["Rank"] = rank;
rank++;
}
gv.DataSource = dt;
gv.DataBind();
}
}
Below is the result I'm getting:
What I really want is:
I was able to fix my problem with the code below:
protected void bindGridView(GridView gv)
{
using(DataTable dt = getData())
{
DataColumn dc_Total = new DataColumn("Total");
DataColumn dc_Rank = new DataColumn("Rank");
dt.Columns.Add(dc_Total);
dt.Columns.Add(dc_Rank);
dc_Rank.SetOrdinal(1);
dc_Total.SetOrdinal(2);
foreach (DataRow dr in dt.Rows)
{
dr["Total"] = Convert.ToDouble(dr["A_B_PERC"].ToString()) + Convert.ToDouble(dr["C_PERC"].ToString());
}
dt.DefaultView.Sort = "Total";
using(DataView dv = dt.DefaultView)
{
int rank = 1;
foreach (DataRowView drv in dv)
{
drv["Rank"] = rank;
rank++;
}
gv.DataSource = dv;
gv.DataBind();
}
}
}
Hope this helps if anyone else is having similar issue.

How to convert DataGridViewRowCollection to DataRow[]

I want to convert DataGridViewRowCollection to DataRow[]
Is there any way like:
DataRow[] rowarray=(DataRow[])(datagridview.Rows);
Or do I have to convert each row using foreach?
You need to convert it to a DataTable first.
DataTable data = (DataTable)(datagridview.DataSource);
Then copy the rows into a DataRow array.
DataRow[] drArray = new DataRow[data.Rows.Count];
data.Rows.CopyTo(drArray, 0);
How about with Linq?
DataRow[] rows = dataGridView1.Rows.Cast<DataGridViewRow>()
.Select(r => r.DataBoundItem as DataRowView)
.Where(drv => drv != null)
.Select(drv => drv.Row)
.ToArray();
I hope this will help. Try it and let us know.
void covertDGVToRowColl()
{
DataRow[] rowColl = new DataRow[dgTemp.Rows.Count]; //dgTemp is the datagridview
DataTable dtTable = new DataTable();
foreach (DataGridViewColumn dgvColumn in dgTemp.Columns)
{
dtTable.Columns.Add(dgvColumn.Name);
}
DataRow newRow;
int i = 0;
foreach (DataGridViewRow dRow in dgTemp.Rows)
{
newRow = dtTable.NewRow();
foreach (DataGridViewColumn dgvColumn in dgTemp.Columns)
{
newRow[dgvColumn.Name] = dRow.Cells[dgvColumn.Name].Value;
}
rowColl[i] = newRow;
++i;
}
}

Get value from dataset cell

I am trying to get the value of a specific cell in a dataset. I have a dataset that has at least two tables(could be more). One of the tables has two columns - Name$ and Value$.
I have to search through the dataset by the name column where the name is "FirstName" and save the value corresponding to that specific name.
Here is what I have so far:
string val = null;
foreach (DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
object item = dr[dc];
if (item.ToString().Equals("Name$"))
{
// store the value for that name
}
}
}
}
Any ideas how this could happen, keeping in mind that there could be many tables in the dataset.
EDIT: Here is the full solution:
foreach (DataTable dt in ds.Tables)
{
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName.ToString().Equals("Name$"))
{
if (row["Name$"].ToString().Equals("FirstName"))
{
firstName = (string)row[row.Table.Columns["Name$"].Ordinal + 1];
}
if (row["Name$"].ToString().Equals("LastName$"))
{
lastName = (string)row[row.Table.Columns["Name$"].Ordinal + 1];
}
}
}
}
}
Use ColumnName property
string val = null;
foreach (DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
if(dc.ColumnName=="Name")
{
//save
}
}
}
}
foreach (DataRow dr in ds.Tables[0].Rows) //Tables[1]....
{
if(dr["ColumName"].ToString()==....)
// store the value for that name
}
for (int i = 0; i < ds.Tables.Count; i++)
{
foreach (DataRow dr in ds.Tables[i].Rows)
{
//dr....
}
}

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;
}
}
}

How to get columns from a datarow?

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
}

Categories