Add row below specific column in datatable

I use the following code to load sql table values ​​in datatable

        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);

And I add salary, dynamically dynamically. But she shows in the first column one by one.

enter image description here

But I need a salary in the Department column, and the total amount in the Salary column. How to do it? enter image description here

+4
source share
5 answers

you can use

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

Instead of calculating Total, you can use Datatable.Compute Method

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

You should write like this after the foreach loop,

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

Hope this helps

0
source

, .

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

ADO.NET, , msdn: DataRow. , , excel.

DataRow row = dt.NewRow();

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

-, * , . , .

:

// dt.Rows.Add("Salary"); <-- remove
dt.Rows.Add("", "Salary", total);

, , :

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

All Articles