Changing Number Formatting of asp:TextBox in ItemTemplate from Code-Behind - c#

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;
}

Related

Adding hyperlinks to labels in certain cases, when dealing with databound repeater

Sounds a bit cluttered, but basically I have a databound repeater. On the ASP side, I have this:
<asp:Label ID="Label2" runat="server" Text='<%#Eval("uMessage") %>'></asp:Label>
I'm using the same template for 4 different datasets, and for 2 of them this should be a hyperlink and for the other 2 it shouldn't. So, I'm guessing you have to add a hyperlink programmatically in the code-behind? Has anyone ever done something like this?
Easiest way without all kinds of code-behind and therefor less code fragmentation, I would say you need a property that is set based on your condition prior to data binding.
protected bool LinkVisible { get; set; }
Then you just do this:
<asp:Label ID="Label2" runat="server" Text='<%#Eval("uMessage") %>' Visible="<%# !LinkVisible %>"></asp:Label>
<asp:HyperLink ID="Link" runat="server" Visible="<%# LinkVisible %>" ><%#Eval("uMessage") %></asp:HyperLink>
This sets the Visible for either the Label or the HyperLink. Visible false means it won't even get rendered. In your markup you can see that there will be a label or a hyperlink and no special things popup from the code behind.
You don't need to add the property LinkVisible, but can do the condition there too.
yes it is possible in code behind on DataItem bound
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label)e.Row.FindControl("Label2");
if (lbl.Text == "your condition")
{
HyperLink yourLink = (HyperLink)e.Row.FindControl("yourID");
yourLink.enabled = false;
}
}

Values GridView in cells

I am trying to get values of string that I keep inside GridView.
When I use regular BoundFields, things work get. I get whatever is needed with:
string my_value = myGrid.Rows [rowIndex].Cells[1].Text;
However, one grid needs to have hyperlinked entries in one of the columns. I did:
<asp:BoundField DataField="domainName"
HeaderText="Domain"
SortExpression="domainName"
HtmlEncode="false"
DataFormatString="<a href=DomainConfiguration.aspx?suffix={0}>{0}</a>"
My ASPX page shows the correctly formed hyperlinks. However, if I retrieve Text for the cell, it returns "<\a href=DomainConfiguration.aspx?suffix=example.com>example.com</a>" [without the two extra slashes], instead of "example.com"
What do I need to do to get GridView working the way I want? [Yes, I would rather use GridView and not another control.]
Thank you.
Instead of asp:BoundField to show hype link it is better use asp:HyperLinkField like:
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="domainName" HeaderText="domainName" DataNavigateUrlFormatString="DomainConfiguration.aspx?suffix={0}" DataTextField="domainName" />
</Columns>
and to get string value of that column you should try this:
string my_value= ((HyperLink)myGrid.Rows[rowIndex].Cells[1].Controls[0]).Text;
instead your asp:Bounfield use
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="editLink" runat="server" onclick='<%#Eval("EditLink") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>

How to set visibility of ASP.net hyperlinkfield dynamically

I have a DataGridView with ASP.net hyperlink fields inside of it. What I'm trying to do is not display a certain hyperlink based on a condition. I have SQL that determines if the hyperlink should be hidden or not, but I'm having trouble getting this to work in the hyperlinks.
I tried <asp:HyperLinkField....Visible="<%= Eval(Condition) %>" /> where Condition is True or False from my SQL query.
Which of course throws the error Cannot create an object of type 'System.Boolean' from its string representation '<%= Eval(Condition)%>' for the 'Visible' property.
So I understand this from Why will <%= %> expressions as property values on a server-controls lead to a compile errors? and other similar questions.
My question now is: what is the workaround? How can I get the hyperlink to display or not based on my condition?
You cannot change HyperLinkField's Visible on runtime, because it does not have a DataBinding event.
Instead, you should not be changing HyperLinkField's Visible value. The problem is the rest of the column will not be aligned properly if you hide a single cell.
Instead, you want to use TemplateField and HyperLink, and hide a link only (leave the table cell by itself). For example,
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="ConditionHyperLink" runat="server"
Visible='<%# Convert.ToBoolean(Eval("Condition")) %>'
Text="Link" />
</ItemTemplate>
</asp:TemplateField>
FYI: Your syntax is not correct; it should be ='<%# Eval("") %>'
My recommendation would be to handle it in the codebehind, most likely handling the RowCreated event, and setting the Visible property of the control there. There might be more context to your application that I'm missing, but that seems like the simplest way.
This is the event: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcreated(v=vs.110).aspx
Other events on the gridview in case that one doesn't meet your needs: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview_events%28v=vs.110%29.aspx

How to Bind database integer value to TextBox in FormView control?

On my page I have FormView control, and I am binding Integer database field to the TextBox that's residing inside a FormView's EditItemTemplate.
<FormView ...>
<EditItemTemplate>
<dx:ASPxTextBox ID="txtDiameter" runat="server" Text='<%# Bind("Diameter") %>' />
...
<EditItemTemplate>
...
</FormView>
My problem is that when Diameter field is null, the txtDiameter gets value of empty string. When I click Update command (if I didn't provide any numerical value in txtDiameter), a client error is raised
Sys.WebForms.PageRequestManagerServerErrorException: is not a valid value for Int32.
I found some post from 2005 that claims that this is happening due to some bug. Well, now is 2012. The only way I figured how to deal with this is by using FormView_ItemUpdating event, to circle through all problematic values and convert them from String.Empty to null.
I am just little suspicious that it's maybe not necessary. Is there another way to deal with this problem?
Bind the editor's Value property instead:
<dx:ASPxTextBox ID="txtDiameter" runat="server" Value='<%# Bind("Diameter") %>' />
Does this work?

Asp.net grdiview: can i format the dataitems in an itemtemplate?

i have this code in an itemtemplate in a gridview:
<%# DataBinder.Eval (Container.DataItem, "DiscountAmount")%>
It's a decimal value, and it shows 20.300000000000, which is technically right, but i'd prefer to show 20.30 or 20,30, depending on the culture.
But i've never been a big fan of gridviews, and the DataBinder.Eval and Container.DataItem haven't been good friends either, and i'm lost with how to use it.
it has a special prefix (<%#) and when i type anything other then the original code it's no good, but changing <%# to <%= or <% doesn't seem to work either?
This will also work:
<%#= String.Format("{0, 0:N2}",DataBinder.Eval (Container.DataItem, "DiscountAmount"))%>
Edit: I share your discomfort with declarative databinding syntax. You can accomplish the same thing in code-behind by calling the RowDataBound event and implementing whatever changes you want to make as the data is bound to the GridViewRow.
To do this, you need to wire up the event in the markup by setting OnRowDataBound to the name of your event handler, something like this:
<asp:GridView ID="InvoiceGrid" OnRowDataBound="InvoiceGrid_RowDataBound".....>
Then you create an event handler in code behind with a signature like this:
protected void InvoiceGrid_RowDataBound(object sender, GridViewRowEventArgs e)
The first thing you do in that event handler is test which type of GridViewRow type it is:
if (e.Row.RowType == DataControlRowType.DataRow)....
Then you do whatever formatting you want to do.
For folks happy with declarative markup, this may seem burdensome. But for people who are comfortable writing code, you can do a whole lot more here in code behind.
Did you try this?
<%= String.Format("{0:0,0.00}", DataBinder.Eval (Container.DataItem, "DiscountAmount"))%>
or just
<%# DataBinder.Eval(Container.DataItem, "DiscountAmount", "{0:0,0.00}")
You can read more format options in the article String Format for Double.
There are several ways...some of them stated above and here is another one:
Text='<%# GetFormattedDiscount(Eval("DiscountAmount").ToString())%>'
GetFormattedDiscout is a function in your code-behind where you can do whatever formatting you need and return it as string:
protected void GetFormattedDiscount(string amount){
return String.Format("{0:N2}",amount);
}
Even this should work:
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#String.Format("{0:n2}",Eval("DiscountAmount")) %>'></asp:Label>
</ItemTemplate>

Categories