在数据表中特定列下添加一行。

4
我使用以下代码将sql表中的值加载到数据表中。
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection("Connection String Here");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from ExportExcel", con);
        dt.Load(cmd.ExecuteReader());
        int total = 0;
        foreach (DataRow row in dt.Rows)
        {
            int salaryvalue = Convert.ToInt32(row["Salary"]);
            total = salaryvalue + total;
        }

        dt.Rows.Add("Salary");
        dt.Rows.Add(total);

我会尽力为您翻译以下内容,这是关于IT技术方面的问题:

我动态地添加了薪水总和,但它们一个接一个地显示在第一列中。

enter image description here

但是我需要在部门列中显示薪水,在薪水列中显示总和。应该如何处理? enter image description here

5个回答

4
您可以使用

标签

     dt.rows.add(new object[]{"","Salary",total });

使用Datatable.Compute Method方法,而不是计算Total。

     object total;
      total= dt.Compute("Sum(Salary)", "");

2
您需要的有关此的 ADO.NET 信息可以在 msdn 上找到:DataRow。您可以像之前所做的那样在代码中计算它,或者在 Excel 文档中插入一个函数。
DataRow row = dt.NewRow();

row["Name"] = "Salary";
row["Salary"] = total;
dt.Rows.Add(row);

1
哈哈..真有趣,或者说很悲哀,那些可以通过查阅MSDN轻松回答的问题总是会得到大量回答,而那些难度较高的问题则被忽视,因为它们没有任何积分/分钟可获得... - Gaute Løken

0

你实际上只想添加一行,所以只需添加一行即可。

dt.Rows.Add(string.Empty, "Salary", total);

0
首先,在查询中不要使用*,这会在未来产生令人讨厌的错误。命名您想要检索的所有列。
您必须为第一列添加一个空字符串:
// dt.Rows.Add("Salary"); <-- remove
dt.Rows.Add("", "Salary", total);

顺便提一下,你也可以使用以下查询来获取总数:

int total = dt.AsEnumerable.Sum(r => r.Field<int>("Salary"));

0

在你的foreach循环之后,你应该这样写:

DataRow drNew=dt.NewRow();
drNew[0]="";
drNew[1]="Salary";
dtNew[2]=total;
dt.Rows.Add(drNew);

希望这能有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接