如何在数据表中应用表达式?

时间:2012-09-26 07:02:03

标签: c# asp.net visual-studio-2010

System.IO.StreamReader rdr = new StreamReader(csvPath.Text);

            DataTable dt = new DataTable("Table");
            dt.Columns.Add(new DataColumn("Date"));              
            dt.Columns.Add(new DataColumn("A.TEMP090835"));
            dt.Columns.Add(new DataColumn("Difference"));

            while ((rowValue = rdr.ReadLine()) != null)
            {
                string[] arr;
                arr = rowValue.Split(',');
                DataRow row = dt.NewRow();
                row["Date"] = arr[0];
                row["A.TEMP090835"] = arr[4];
                row["Difference"] = //here is the problem
                dt.Rows.Add(row);

            }
            dt.Rows.RemoveAt(0);
            dataGridView2.DataSource = dt;
            rdr.Close();

此代码生成一个包含3列的数据表..... Date,A.TEMP ...和Difference。我正在导入数据的csv文件没有第3列,即“差异”。我需要为该列编写一个表达式......通过以下csv文件可以理解其逻辑:

日期,A.TEMP090835,差异

10/28 / 2011,25.56,0

10/28 / 2011,26.65,26.65 - 25.56

10/28 / 2011,27.11,27.11 - 25.56

10/28 / 2011,29.43,29.43 - 25.56

2011年10月28日,30.29,30.29 - 25.56

10/28 / 2011,31.57,31.57 - 25.56

10/28 / 2011,32.82,32.82 - 25.56

10/28 / 2011,34.07,34.07 - 25.56

如何填写“差异”栏?

1 个答案:

答案 0 :(得分:0)

使用临时变量可以实现

        System.IO.StreamReader rdr = new StreamReader(csvPath.Text);

        DataTable dt = new DataTable("Table");
        dt.Columns.Add(new DataColumn("Date"));              
        dt.Columns.Add(new DataColumn("A.TEMP090835"));
        dt.Columns.Add(new DataColumn("Difference"));
    double d=0;
        while ((rowValue = rdr.ReadLine()) != null)
        {
            string[] arr;
            arr = rowValue.Split(',');
            DataRow row = dt.NewRow();
            row["Date"] = arr[0];
            row["A.TEMP090835"] = arr[4];
            row["Difference"] = Convert.ToDouble(arr[4])-d;
            dt.Rows.Add(row);
    d=Convert.ToDouble(arr[4]);

        }
        dt.Rows.RemoveAt(0);
        dataGridView2.DataSource = dt;
        rdr.Close();

不确定你是否可以通过获取前一行来表达式。

从o'reilly http://ondotnet.com/pub/a/dotnet/2003/05/26/datacolumn_expressions.html

查看