Find the dataRow index

Asked

Viewed 723 times

0

I’m walking a DataTable with a foreach using a variable of type DataRow, but I need to recover the content of DataRow that I’m walking through.

foreach(DataRow row in DataTable.Rows)
{
     string descricao = Convert.ToString(row["id"] +" - "+ row["nome"]);
     int index = ??;
     int value = Convert.ToInt32(row["id"]);
     checkedListBoxControl1.Items.Add(value);
     checkedListBoxControl1.Items[index].Description = descricao;
}
  • The answer answered what you wanted? Something needs to be improved?

  • yes, sorry I forgot to accept the answer;

  • Relax, I just wanted to know if there was something missing =D

1 answer

1


It is possible to use the method IndexOf() of DataTable

foreach(DataRow row in DataTable.Rows)
{         
     int index = DataTable.Rows.IndexOf(row); 
}

However, the DataTable will always be in order, so it is possible to control the index yourself.

int index = 0;
foreach(DataRow row in DataTable.Rows)
{        
     index++;
}

Or else, it is possible to change the foreach by a for and capture the DataRow by the collection Rows using the index

for(int index = 0; index < DataTable.Rows.Count; index++)
{
    // "index" é o index que você precisa
    var row = DataTable.Rows[index];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.