问题
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