Iterate through DataTable (row number)

S

sck10

Hello,

When iterating through a datatable, how do you get the row that you are on?
I would like to replace "i" with the row number.

Thanks,

sck10

int i = 0;
string strBarName = string.Empty;
foreach(DataRow drSearch in dtSearch.Rows)
{
drRow = dtSearch.Rows;
strBarName = drRow[0].ToString();
i++;
}
 
G

Guest

Howdy,

You mixed two methods obtaining the item in a collection: enumerator
(foreach statment) and iterator ([index]):

1. enumerator

string barName;

foreach (DataRow row in dtSearch.Rows)
{
// access value by column name
barName = row["barName"].ToString();
// or access value by column index
barName = row[0].ToString();
}

2. iterator

for (int i = 0; i < dtSearch.Rows.Count; i++)
{
DataRow row = dtSearch.Rows;

// access value by column name
barName = row["barName"].ToString();
// or access value by column index
barName = row[0].ToString();
}

Hope it's clear now
 
S

sck10

Thanks for help Milosz, works perfect.

sck10



Milosz Skalecki said:
Howdy,

You mixed two methods obtaining the item in a collection: enumerator
(foreach statment) and iterator ([index]):

1. enumerator

string barName;

foreach (DataRow row in dtSearch.Rows)
{
// access value by column name
barName = row["barName"].ToString();
// or access value by column index
barName = row[0].ToString();
}

2. iterator

for (int i = 0; i < dtSearch.Rows.Count; i++)
{
DataRow row = dtSearch.Rows;

// access value by column name
barName = row["barName"].ToString();
// or access value by column index
barName = row[0].ToString();
}

Hope it's clear now
--
Milosz


sck10 said:
Hello,

When iterating through a datatable, how do you get the row that you are
on?
I would like to replace "i" with the row number.

Thanks,

sck10

int i = 0;
string strBarName = string.Empty;
foreach(DataRow drSearch in dtSearch.Rows)
{
drRow = dtSearch.Rows;
strBarName = drRow[0].ToString();
i++;
}
 

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