获取for循环到外部循环到数组的值?

时间:2017-07-07 06:30:44

标签: c# for-loop datagridview

这是我的代码。

          for (int i = 1; i < dataGridView2.RowCount - 1; i++)
                {

                    int valueCellIndex = 3;//assume calculate the 0th column
                    int resultCellIndex = 4;//assume result to put into the 1th column
                    var lastRow = dataGridView2.Rows[i - 1];
                    var curRow = dataGridView2.Rows[i];
                    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
                    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);

                    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last); //

                }
          JsonArray.Add(new JsonInput(close, gain));

如何让循环进入JsonArray'获得'?

1 个答案:

答案 0 :(得分:1)

由于增益变量是整数类型,您可以创建一个List对象以在循环内添加增益变量值。稍后将整数List转换为json数组。

List<int> gainList = new List<int>();
for (int i = 1; i < dataGridView2.RowCount - 1; i++)
{

    int valueCellIndex = 3;//assume calculate the 0th column
    int resultCellIndex = 4;//assume result to put into the 1th column
    var lastRow = dataGridView2.Rows[i - 1];
    var curRow = dataGridView2.Rows[i];
    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);    
    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last);
    gainList.Add(gain);
}

要将列表转换为json格式,您可以使用System.Web.Script.Serialization命名空间。

using System.Web.Script.Serialization;
.....
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(gainList);