我正在尝试使用此方法在Datatable中添加元素。 我收到这个错误:
System.Data.dll中出现未处理的“System.IndexOutOfRangeException”类型异常
附加信息:位置0没有行。
public DataTable slope(DataTable createPath)
{
DataTable slopes = new DataTable();
slopes.Columns.Add("Slope Line 1", typeof(double));
slopes.Columns.Add("Slope Line 2", typeof(double));
slopes.Columns.Add("Direction 1", typeof(string));
slopes.Columns.Add("Direction 2", typeof(string));
for (int i = 2; i < createPath.Rows.Count; i++)
{
slopes.Rows[i - 2][0] = Math.Atan2((Convert.ToDouble(createPath.Rows[i - 1][2]) - Convert.ToDouble(createPath.Rows[i - 2][2])),
(Convert.ToDouble(createPath.Rows[i - 1][1]) - Convert.ToDouble(createPath.Rows[i - 2][1])));
slopes.Rows[i - 2][1] = Math.Atan2((Convert.ToDouble(createPath.Rows[i][2]) - Convert.ToDouble(createPath.Rows[i - 1][2])),
(Convert.ToDouble(createPath.Rows[i][1]) - Convert.ToDouble(createPath.Rows[i - 1][1])));
}
for (int j = 0; j < slopes.Rows.Count; j++ )
{
for (int k=0; k<2; k++)
{
if ( Convert.ToDouble(slopes.Rows[j][k])== 0)
slopes.Rows[j][k + 2] = "Straight Right";
else if (Convert.ToDouble(slopes.Rows[j][k]) == Math.PI)
slopes.Rows[j][k + 2] = "Straight Left";
else if (Convert.ToDouble(slopes.Rows[j][k]) == (Math.PI / 2))
slopes.Rows[j][k + 2] = "Straight Up";
else if (Convert.ToDouble(slopes.Rows[j][k]) == -(Math.PI / 2))
slopes.Rows[j][k + 2] = "Straight Down";
else
slopes.Rows[j][k + 2] = "Slant";
}
}
return slopes;
}
答案 0 :(得分:1)
在尝试访问slopes
slopes.Rows[i - 2]
表添加行
for (int i = 2; i < createPath.Rows.Count; i++)
{
var row = slopes.NewRow();
row[0] = Math.Atan2((Convert.ToDouble(createPath.Rows[i - 1][2]) - Convert.ToDouble(createPath.Rows[i - 2][2])),
(Convert.ToDouble(createPath.Rows[i - 1][1]) - Convert.ToDouble(createPath.Rows[i - 2][1])));
row[1] = Math.Atan2((Convert.ToDouble(createPath.Rows[i][2]) - Convert.ToDouble(createPath.Rows[i - 1][2])),
(Convert.ToDouble(createPath.Rows[i][1]) - Convert.ToDouble(createPath.Rows[i - 1][1])));
slopes.Rows.Add(row);
}
答案 1 :(得分:0)
slopes.Rows.Add(What you are adding);