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

Add column to datatable and bind it in grid

我有一个带有 属性 autogeneratecolumn=true 的网格视图 我的 DataTable 正在使用 mdx 查询填充数据,如下所述。

sales2015   sales2014
1256           1235
3569            0
0              1235

我想添加另一个名为 "VARIENT" 的列,并且需要在其中显示百分比。

Formula: (sales2015 - sales2014)/sales2015 * 100

需要使用相同的公式计算数据表的每一行并绑定到 gridview。

请帮我理一下逻辑。

Note : my grid is having autogenerated columns

预期结果是这样的

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

我的代码部分是:

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

您可以即时创建第三列并像这样填充它:-

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

您需要相应地更改您的公式。

更新:

如果您的列名将发生变化,那么您可以使用列索引(但如您所知,如果您的数据表结构动态变化,它可能会失败),如下所示:-

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