Iterating through the rows of a dataview

A

Anita C

Hi,
I'd like to be able to iterate throught the rows of a dataview but only 2
particular cols. of the dataview - col1 & col.4, to populate an array with
the values for the particular columns for all the rows in the dataview. My
problem is that I don't know how to access the particular cols. while
reading each row. How do I achieve the above? A code sample will be great.
Thanks in advance
 
R

Ravi[MSFT]

This is what you can do while iterating through the rows. You can access
each DataRowView from the DataView and access the column values on the
DataRowView and populate your object array, like in the following:
----
int rowCount = 0;
object[][] objArr = new object[dv.Count][];
foreach (DataRowView drv in dv) {
objArr[rowCount] = new object[2];
objArr[rowCount][0] = drv["Name"];
objArr[rowCount][1] = drv["Age"];
rowCount++;
}
----

A more complete code sample is below:
-----------
using System;
using System.Data;

class Test {
public static void Main()
{
try {
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Customers");
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
DataView dv = new DataView(dt);
dv.Sort = "Age ASC";

dt.Rows.Add(new object[] { 1, "X", 30 });
dt.Rows.Add(new object[] { 2, "Y", 35 });
dt.Rows.Add(new object[] { 3, "Z", 20 });

int rowCount = 0;
object[][] objArr = new object[dv.Count][];
foreach (DataRowView drv in dv) {
objArr[rowCount] = new object[2];
objArr[rowCount][0] = drv["Name"];
objArr[rowCount][1] = drv["Age"];
rowCount++;
}
} catch (Exception exc) {
Console.WriteLine(exc);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top