问题描述:

I need to dynamically change the 'number format' of a textbox that is inside an itemTemplate. Nothing I've tried is working and I would appreciate some ideas.

A very simplified version of the original code is this:

<asp:GridView ID="gv1">

<Columns>

<asp:TemplateField HeaderText="Xfer From">

<ItemTemplate>

<asp:TextBox ID="txtTransferFrom" runat="server" Text='<%# Bind ("FundValueTransferFrom", "{0:0.00}") %>' />

<asp:RangeValidator ID="val1" runat="server" ControlToValidate="txtTransferFrom" Type="Currency" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

Please notice the decimal formatting ("{0:0.00}") and the Currency type of the bound field.

Now what I need to do is, based on the setting of a radio button on this page, change that formatting. In one state, it needs to be currency with two decimal places; in the other it must be a percentage out to three decimal places.

It sounds straightforward but I can't make it work. Ideally I would like to put some code in the 'radioButton_SelectedIndexChanged' method but I can't seem to access that formatting from there.

I also tried using an "if" statement in inline code (<% %>) on the ASPX page, but it doesn't respond to the changing of the radio buttons. I must mention that this grid is inside an update panel... I tried calling UP.Update() but it doesn't fix the problem. I did remove the initial formatting from the ASPX page so that it won't interfere -- nothing.

One solution might have been to format the number strings in the code-behind, but I can't -- the grid is bound to an object whose fields are "doubles" not strings... the conversion to strings is happening implicitly in the data binding.

Doesn't anyone have another approach I might try to switch this formatting programmatically? Thanks in advance for any insight!

网友答案:

Dacker, your comment put me on a good path towards an answer--many thanks! I still have other issues to deal with, but the code below appears to be doing the trick for this immediate issue.

In the ASPX (abbreviated tag):

<asp:TextBox ID="txtTransferFrom" ... " Text='<%# Eval("FundValueTransferFrom") != null ? GetFormattedString((double)Eval("FundValueTransferFrom")) : Eval("FundValueTransferFrom") %>' ...">

And in the code-behind:

public string GetFormattedString(double val)
        {
            string newVal;
            if (rblFtmp1.Text == DOLLAR)
            {
                newVal = String.Format("{0:0.00}", val);
            }
            else // If not DOLLAR then it's PERCENT
            {
                newVal = String.Format("{0:0.000}", val);
            }
            return newVal;
        }
相关阅读:
Top