使用DataColumn的Expression属性从ChildRows获取连接文本

时间:2017-07-26 08:37:47

标签: c# expression datacolumn

我在两个DataTable中有DataSet,MasterTable与DetailTable有PK关系链接。我知道表达可以帮助总结孩子的价值,如

dtMaster.Columns.Add(new DataColumn("TotalQty", 0, "Sum(child.Qty)"));

但是我需要连接字符串,比如

dtMaster.Columns.Add(new DataColumn("HasErrors", 0, "Concat(child.ErrorText + ';')"));

我知道列表达式不支持concat,所以现在我需要检测Table.ColumnChanging事件来手动设置master的HasError字段值。

有人会以更自动的方式告诉我吗?

这是我的示例代码

    internal static void Test()
    {
        var ds = new DataSet();

        var dtMaster = ds.Tables.Add("Master");

        var colIDMaster = dtMaster.Columns.Add("ID");

        var dtDetail = ds.Tables.Add("Detail");

        var colIDDetail = dtDetail.Columns.Add("ID");
        dtDetail.Columns.Add("CID");
        dtDetail.Columns.Add("Qty", typeof(int));
        dtDetail.Columns.Add("ErrorText", typeof(string), "IIF(Qty is null, 'Qty err', '')");

        ds.Relations.Add("m2d", colIDMaster, colIDDetail, false);

        //I know I can do this
        dtMaster.Columns.Add("TotalQty", typeof(int), "Sum(child.Qty)");
        //here is I am asking solution
        //dtMaster.Columns.Add("ContainErrors", typeof(string), "Concat(child.ErrorText + ';')");

        var newMasterRow = dtMaster.NewRow();
        newMasterRow["ID"] = "A";
        dtMaster.Rows.Add(newMasterRow);

        var newDetailRow = dtDetail.NewRow();
        newDetailRow["ID"] = "A";
        newDetailRow["CID"] = "D1";
        newDetailRow["Qty"] = DBNull.Value;
        dtDetail.Rows.Add(newDetailRow);

        newDetailRow = dtDetail.NewRow();
        newDetailRow["ID"] = "A";
        newDetailRow["CID"] = "D2";
        newDetailRow["Qty"] = 10;
        dtDetail.Rows.Add(newDetailRow);

        //now I can loop and print the  master row with ID and it's ErrorTexts
    }

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要在详细信息中添加列值更改事件。

   dtDetail.ColumnChanged += dtDetail_ColumnChanged;

    static void dtDetail_ColumnChanged(object sender, DataColumnChangeEventArgs e)
    {
        if (e.Column.ColumnName == "Qty")
        {
            int sum = 0;
           // dtMaster.Columns.Add("TotalQty"
            foreach(DataRow row in ds.Tables["Detail"].Rows)
            {
                if (row["Qty"] != DBNull.Value && Convert.ToString(row["CID"]) != Convert.ToString(e.Row["CID"]))
                {
                    sum += Convert.ToInt32(row["Qty"]);
                }
            }

            sum += Convert.ToInt32(e.Row["Qty"]);

            ds.Tables["Master"].Rows[0]["TotalQty"] = sum;

        }
    }