基于运行时先前的行计算,将数据行添加到数据表中

时间:2011-03-01 12:44:41

标签: c#

我有以下数据表(请注意列号在编译时不会知道

DataTable dt = new DataTable();
dt.Columns.Add("Summary");
dt.Columns.Add("Beta");
dt.Columns.Add("Delta");

dt.Rows.Add("Summary1", "n/a", "1");           
dt.Rows.Add("Summary2", "1.00", "2");

现在,对于这个数据表,我必须再添加一行,这将是减法的 dt.Rows [0] .Columns [i + 1] - dt.Rows [1] .Columns [i + 1]

其中i = 0

所以最终的数据表将是

Summary   Beta  Delta   
---------------------------------
Summary1  n/a   1
Summary2  1.00  2
Summary3  n/a   -1

我是dotnet的新手。请帮忙

2 个答案:

答案 0 :(得分:1)

我不确定你的意思,但在你的决赛桌上,我能想到这个:

DataRow summary1 = dt.Rows[0], summary2 = dt.Rows[1], summary3 = new DataRow();
summary3[0] = "Summary3";

for(int i=1; i < summary1.Table.Columns.Count; i++)
{
  try{
    summary3[i] = double.Parse(summary1[i].ToString()) - double.Parse(summary2[i].ToString())
  }catch{
    summary3[i] = "n/a";
  }
}

此代码允许您在DataColumn

中包含可变数量的DataRow

答案 1 :(得分:1)

我也不确定你想要什么,但我认为你在列中的字符串出现问题并将它们转换为int和back。以下是执行转换的代码示例:

    private string CalculateColumnTotal(int row, int column)
    {
        int column1Value;
        bool parsed = int.TryParse(_table.Rows[row][column].ToString(), out column1Value);
        if (!parsed) return "n/a";

        int column2Value;
        parsed = int.TryParse(_table.Rows[row + 1][column].ToString(), out column2Value);
        if (!parsed) return "n/a";

        var total = column1Value - column2Value;
        return total.ToString();
    }
}

完整的表单代码如下所示:

public partial class Form1 : Form
{
    private readonly DataTable _table = new DataTable("Table");

    public Form1()
    {
        InitializeComponent();
        _table.Columns.Add("Summary");
        _table.Columns.Add("Beta");
        _table.Columns.Add("Delta");

        const int rowPairs = 1;
        for (int i = 0; i <= rowPairs - 1; i++)
        {
            _table.Rows.Add("Summary1", "n/a", 1);
            _table.Rows.Add("Summary2", 1.00, 2);
            _table.Rows.Add("Summary3", null, null);
        }

        for (int row = 0; row < _table.Rows.Count - 1; row += 3)
        {
            string columnOneTotal = CalculateColumnTotal(row, 1);
            string columnTwoTotal = CalculateColumnTotal(row, 2);
            _table.Rows[row + 2][1] = columnOneTotal;
            _table.Rows[row + 2][2] = columnTwoTotal;
        }

        dataGridView1.DataSource = _table;
    }

    private string CalculateColumnTotal(int row, int column)
    {
        int column1Value;
        bool parsed = int.TryParse(_table.Rows[row][column].ToString(), out column1Value);
        if (!parsed) return "n/a";

        int column2Value;
        parsed = int.TryParse(_table.Rows[row + 1][column].ToString(), out column2Value);
        if (!parsed) return "n/a";

        var total = column1Value - column2Value;
        return total.ToString();
    }
}