Edit all rows in a column, c # data table
I have a data table filled with data from a file that has been read. I want to then edit all the rows in a specific column. In my case, dividing the speed column by 1.6 to convert to MPH from KMH.
i tried below code but i am getting index out of range
foreach (DataRow row in data_table.Rows) {
row["Speed (KM/H)"] = speed[x]/1.6;
}
here is the code that populates 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;
}
source to share
You can use extensions Field
and SetField
, which are strongly typed, otherwise you have to cast fields manually from object to int
. You are getting an exception IndexOutOfRange
because it x
appears to be an invalid index. Use a 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);
}
source to share