How to set a gridView column's text depending on other columns which are binded?

穿精又带淫゛_ 提交于 2019-12-13 04:41:09

问题


I have a GridView in ASP which I use for displaying products in a shopping cart.

I set the source of GridView the ShopDataSet and the columns Name, Price and Quantity are filled automatically.

What I want to achieve is a new column, added by me, which displays the cost of each row i.e. Cost = price * quantity;

How can I do this programatically, without executing a new query on the database?

I have to say that on Price and Quantity I set format like "${0}" for Price and "{0} piece(s)" for Quantity.


回答1:


You should populate your datasource programmatically.

Get the results in a SqlDataReader and populate a DataTable with the results of the SqlDataReader.

Now create a new DataTable with columns that match the output that you want including Cost in your case. Now iterate through each row of the 1st DataTable and add rows to the new DataTable with the cost calculation.

For Example,

DataTable oldTable = new DataTable();
oldTable .Load(rdr); // where rdr is your SqlDataReader

Now create your new table

DataTable newTable = new DataTable();
DataColumn noteID = new DataColumn("Cost", typeof(string));
newTable.Columns.Add(noteID);
//Add other columns
foreach (DataRow row in oldTable .Rows)
{
   DataRow newRow = newTable.NewRow();
   newRow["Cost"] = //your calculation
   ...
   ...
   newTable.Add(newRow);
}

Now set the DataSource of your grid to NewTable



来源:https://stackoverflow.com/questions/10588329/how-to-set-a-gridview-columns-text-depending-on-other-columns-which-are-binded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!