Iterate through DataTable (row number)

  • Thread starter Thread starter sck10
  • Start date Start date
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++;
}
 
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
 
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++;
}
 
Back
Top