Editing the column of an objectdatasource before databind
-
15-07-2021 - |
Question
Currently I'm using a gridview with an objectdatasource to display a table of product info. I also have a drop down list to switch the view between Imperial and Metric units. To switch between the two, every time someone changes the drop down list selection, I am deleting the old units column and inserting a new column based on the selection, as follows:
if (GridView1.Columns.Count > 7)
JobListGridView.Columns.Remove(GridView1.Columns[7]);
BoundField colIndex8 = new BoundField();
colIndex8.HeaderText = "Units";
if (UnitsDropDown.Text == "Imperial")
{
colIndex8.DataField = "IUnits";
colIndex8.SortExpression = "IUnits";
GridView1.Columns.Add(colIndex8);
}
else
{
colIndex8.DataField = "MUnits";
colIndex8.SortExpression = "MUnits";
GridView1.Columns.Add(colIndex8);
}
GridView1.DataBind();
This works to change the units being displayed in the units column (e.g. from "mm" to "ft"). However, I also need to change the value of another column that displays length. Is it possible to somehow edit the values in the length column (say multiply by a constant) and then databinding the modified column to the gridview without having to create a new column in the database table to store this information?
I am imagining something like:
DataColumn dc = GridView1.Columns[4];
foreach (cell c in dc)
{
c *= 0.5;
}
GridView1.Columns.Add(dc);
GridView1.DataBind();
As simple pseudo-code, but is this the right approach/is this possible?
Thanks
Solution
Don't add and remove columns. Just hide the column you don't want to see:
<asp:BoundField DataField="IUnits" Visible="<%# UnitsDropDown.Text == "Imperial" %>" />
<asp:BoundField DataField="MUnits" Visible="<%# UnitsDropDown.Text != "Imperial" %>" />
As for your second question, use a TemplateField:
<asp:TemplateField HeaderText="foo">
<ItemTemplate>
<asp:Label runat="server" Text='<%# ((int)Eval("foo")) * (UnitsDropDown.Text == "Imperial" ? 0.5 : 1) %>' />
</ItemTemplate>
</asp:TemplateField>