简体   繁体   中英

Add column to datatable and bind it in grid

I have a gridview with property autogeneratecolumn=true and my DataTable is filling the data as mentioned below using mdx query.

sales2015   sales2014
1256           1235
3569            0
0              1235

i want to add another column named "VARIENT" and need to show the percentages in the same.

Formula: (sales2015 - sales2014)/sales2015 * 100

Need to calulate each row for the datatable using same formula and bind to gridview.

please help me with the logic.

Note : my grid is having autogenerated columns

expected result is like this

sales2015   sales2014  Varient
1256           1235      **%
3569            0         **%
0              1235      **%  

My Code part is:

System.Data.DataTable dt = new System.Data.DataTable();
ViewData1 vData = new ViewData1();
dt = vData .__getCustomerSource()// Here in this function i was filling the datatable and returing

DataGrid1.DataSource = null;

DataGrid1.DataSource = dt;
DataGrid1.DataBind();

You can create the third column on the fly and populate it like this:-

dt = vData .__getCustomerSource()
dt.Columns.Add("Varient", typeof(string));
foreach (DataRow row in dt.Rows)
 {
    row["Varient"] = String.Format("{0} %", ((row.Field<int>("sales2015") - 
                        row.Field<int>("sales2014")) / row.Field<int>("sales2015")) * 100);
 }
DataGrid1.DataSource = dt;
DataGrid1.DataBind();

You need to change your formula accordingly.

Update:

If your column names will be changing then you can make use of column index (but as you know it may fail if your datatable structure change dynamically) like this:-

(int)row.[1] - (int)row[2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM