简体   繁体   English

将列添加到数据表并将其绑定到网格

[英]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. 我有一个属性为autogeneratecolumn=true的gridview,我的DataTable正在使用mdx查询填充数据,如下所述。

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. 我想添加一个名为“ VARIENT”的列,并需要在同一列中显示百分比。

Formula: (sales2015 - sales2014)/sales2015 * 100 公式: (sales2015 - sales2014)/sales2015 * 100

Need to calulate each row for the datatable using same formula and bind to gridview. 需要使用相同的公式计算数据表的每一行并绑定到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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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