Reputation: 133
I've got a data table that's populated with data from a file that's been read in. I wish to then edit all rows in a specific column. In my case dividing the speed column by 1.6 to convert to MPH from KMH.
so far, I've tried using the below code but am getting an index out of range
foreach (DataRow row in data_table.Rows) {
row["Speed (KM/H)"] = speed[x]/1.6;
}
here is the code that fills the data table with the file
private void display_hrm_data() {
/* array heart_rate_table set to heart_rate
* adds each column
* for every piece of data in heart_rate_table add rows
*/
data_table.Columns.Add("Heart Rate (BPM)", typeof(string));
data_table.Columns.Add("Speed (KM/H)", typeof(int));
data_table.Columns.Add("Cadence (RPM)", typeof(int));
data_table.Columns.Add("Altitude (M)", typeof(int));
data_table.Columns.Add("Power (Watts)", typeof(int));
data_table.Columns.Add("Time (Seconds)", typeof(int));
for (int x = 0; x < heart_rate.Count - 1; x++) {
time = time + 1;
data_table.Rows.Add(heart_rate[x],speed[x],cadence[x],altitude[x],power[x], time);
}
dgv_data.DataSource = data_table;
}
Upvotes: 4
Views: 2388
Reputation: 460168
You can use the Field
and SetField
extensions which are strongly typed, otherwise you need to cast the fields manually from object to int
. You get the IndexOutOfRange
exception because x
seems to be an invalid index. Use the column name.
So for example:
DataColumn speedCol = data_table.Columns["Speed (KM/H)"];
foreach (DataRow row in data_table.Rows)
{
int oldSpeed = row.Field<int>(speedCol);
row.SetField(speedCol, oldSpeed / 1.6);
}
Upvotes: 2