[英]Add a row under specific column in datatable
我使用以下代碼將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);
我動態地添加了Salary,但它在第一列中逐一顯示。
但是我需要在部門欄中的薪水,以及薪資欄中的總額。如何做到這一點?
您可以使用
dt.rows.add(new object[]{"","Salary",total });
您可以使用Datatable.Compute Method
而不是計算Total
object total;
total= dt.Compute("Sum(Salary)", "");
在你的foreach循環之后,你應該這樣寫
DataRow drNew=dt.NewRow();
drNew[0]="";
drNew[1]="Salary";
dtNew[2]=total;
dt.Rows.Add(drNew);
希望這可以幫助
您實際上只想添加一行,因此只需添加一行。
dt.Rows.Add(string.Empty, "Salary", total);
您可以在msdn: DataRow中找到所需的ADO.NET信息。 你可以在代碼中計算它,就像你已經完成或在excel文檔中插入一個函數。
DataRow row = dt.NewRow();
row["Name"] = "Salary";
row["Salary"] = total;
dt.Rows.Add(row);
首先,不要在查詢中使用*
,這將在以后產生令人討厭的錯誤。 為要檢索的所有列命名。
您必須為第一列添加一個空字符串:
// dt.Rows.Add("Salary"); <-- remove
dt.Rows.Add("", "Salary", total);
順便說一下,您還可以使用以下查詢來獲取總計數:
int total = dt.AsEnumerable.Sum(r => r.Field<int>("Salary"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.