![](/img/trans.png)
[英]Bind DataTable to Datagridview that already have column defined into data grid
[英]Add column to datatable and bind it in grid
我有一个属性为autogeneratecolumn=true
的gridview,我的DataTable正在使用mdx查询填充数据,如下所述。
sales2015 sales2014
1256 1235
3569 0
0 1235
我想添加一个名为“ VARIENT”的列,并需要在同一列中显示百分比。
公式:
(sales2015 - sales2014)/sales2015 * 100
需要使用相同的公式计算数据表的每一行并绑定到gridview。
请帮助我的逻辑。
注意:我的网格具有自动生成的列
预期的结果是这样的
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.