Find the index of dataRow

0

I'm traversing a DataTable with a foreach using a variable of type DataRow , however I'm having to retrieve the index of the DataRow I'm traversing.

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;
}
    
asked by anonymous 23.02.2017 / 15:17

1 answer

1

You can use the IndexOf() of DataTable

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

However, DataTable will always be in order, so you can control the index yourself.

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

Or, you can change foreach by for and capture DataRow by Rows collection using index

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