Can I negate the value in an attribute that uses an "Eval"? - asp.net

I'd like to set a button's enabled state to be the negation of a value.
So given this code:
<asp:CheckBox ID="DefaultChecked"
Checked='<%# Bind("IsDefaultMessage") %>'
Enabled="false"
runat="server" />
<asp:LinkButton ID="MakeDefaultButton"
runat="server"
CommandName="MakeDefault'
CommandArgument='<%# Bind("ResidentialInfoID") %>'
Text="Make Default" />
How can I make the LinkButton Enabled attribute false if IsDefaultMessage == true?

Use Eval instead of Bind. Bind is for two-way binding, i.e. for cases where you need to be able to save the data back to your data source.
When you use Bind, the compiled page will actually have generated code that uses Eval to set the value, plus some code to read out the value for saving. Because Bind is replaced with generated code, you can't use any extra logic with Bind.
<asp:CheckBox ID="DefaultChecked" Checked='<%# !(bool)Eval("IsDefaultMessage") %>' Enabled="false" runat="server" />
<asp:LinkButton ID="MakeDefaultButton" runat="server" CommandName="MakeDefault' CommandArgument='<%#Bind("ResidentialInfoID") %>' Text="Make Default"/>

If you can use Eval, it is just a method of the Control class. It's only special in that it needs to be in the context of a data bound block <%# ... %>. Other than that, you can basically treat the block like a regular <%= %> expression block:
<%# !(bool)Eval("IsDefaultMessage") %>
If you want to still Bind it (Eval isn't round-trip), than you'll need to negate it back and forth during databinding. You may not need to do this though, if you can just re-word the control. For example, if a check box, instead of labelling it "Is Not Default Message" to the user and negating it back and forth, than lable it "Is Default Message". Contrived example, but you get the idea.

In case someone is looking for an option with VB.Net
<asp:CheckBox ID="DefaultChecked" Checked='<%# NOT (Eval("IsDefaultMessage")) %>' Enabled="false" runat="server" />

I've never used Bind but my understanding is that it is similar to Databinder.Eval. Either way, both methods return objects so you need to cast it to a boolean before evaluating it.
<%# !Convert.ToBoolean(Bind("IsDefaultMessage") %>
Edit: Looks like this can't be done and using a SqlDataSource on the page would solve the problem. http://forums.asp.net/t/1009497.aspx.

As I recall (It's been a while), there's no particular magic in <%#Bind(. It's just #Bind( inside <%....%>. Which means you'd want:
<% ! #Bind("IsDefaultMessage") %>'

The code
Checked='<%# Eval("IsDefaultMessage").ToString().Length() > 4 %>'
will return true if IsDefaultMessage is false
Since "False".Length = 5 and "True".Length = 4

Related

Set value for 'visible' property in ASPX page programatically

I am trying to set the visible property for a label to either true or false depending on a condition. This is in ASPX page. I am doing something wrong and getting error when this is executed.
<td><asp:Label ID="Label23" runat="server" Text='CERTIFIED'
Visible='<%# DataBinder.Eval(Container.DataItem, "IsAuthorized") > 0%>'>
</asp:Label></td>
Error I am getting is below.
Compiler Error Message: CS0019: Operator '>' cannot be applied to
operands of type 'object' and 'int'
What changes need to be done?
All I need to do set the visible property of the LABEL to true when 'IsAuthorized' is greater than zero.
That's because you have a syntax error, you silly bunny.
Here you are, it should be like this:
<td><asp:Label ID="Label23" runat="server" Text='CERTIFIED' Visible='<%# DataBinder.Eval(Container.DataItem, "IsAuthorized") %>' /></td>
You had an extra > and a 0 in there somewhere.
Also, since you aren't doing anything between the <asp:Label and </asp:Label>, you can close it with an end slash and skip a separate ending tag. Like this <asp:Label ... />
ALSO, sometimes trying to set a visible property like that causes problems, the program can complain that the value wasn't a Boolean. You might want to also ad an explicit conversion like this:
Visible='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "IsAuthorized")) %>'
Assuming that IsAuthorized is a bit type, just cast it to a boolean:
Visible='<%#Convert.ToBoolean(Eval("IsAuthorized"))%>'
Note on a server side control you can do this:
<someControl id="myId" runat="server" Visible='<%# this.SomeField > 5 %>'>
But it won't work unless you call DataBind in the code behind, such as in Page_Load:
myId.DataBind():
Assuming IsAuthorized is an integer, you should use this:
Visible='<%# ((int)DataBinder.Eval(Container.DataItem, "IsAuthorized")) > 0 %>'
Eval returns an object, so you have to cast it to an integer first.
<td><asp:Label ID="Label23" runat="server" Text='CERTIFIED' Visible='<%# (int)(DataBinder.Eval(Container.DataItem, "IsAuthorized")) > 0 %>' ></asp:Label></td>

asp.net repeater with usercontrol - setting commandargument

I have the following repeater code:
<asp:Repeater ID="repMain" runat="server" OnItemCommand="repMain_ItemCommand" EnableViewState="false">
<ItemTemplate>
<dmg:testcontrol runat="server" MyData=<%#Container.DataItem %>>
</dmg:testcontrol>
</ItemTemplate>
</asp:Repeater>
The testcontrol usercontrol looks like:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="TestRepeater.TestControl" %>
<asp:Literal runat="server" ID="litMain" Text="<%#MyData.MyValue %>"></asp:Literal>
<asp:DropDownList runat="server" ID="dropdownMain"></asp:DropDownList>
<asp:Button runat="server" ID="btnMain" Text="Click Me" CommandName="Update" CommandArgument="<%#dropdownMain.SelectedValue%>"/>
Is it possible for me to send through the dropdownMain.SelectedValue as the CommandArgument?
Just now it is an empty string.
Thanks
Duncan
PS This is related to ASP.NET Repeater not binding after ItemCommand but I thought the two sufficiently different to keep apart.
A bit old question but I just my self found the answer to this one.
CommandArgument="<%#dropdownMain.SelectedValue%>"
Needs to look like this instead with single quotes! All inline codes within a asp.net controls have to be done this way instead.
CommandArgument='<%#dropdownMain.SelectedValue%>'
Why not get the selected value, and use it inside the Command function ?
(why to try to send it as argument, from the moment you can get it inside the command called function and its the same)

How to create RouteUrls with databound parameters declaratively?

I'm using the new Routing feature in ASP.NET 4 (Web forms, not MVC). Now I have an asp:ListView which is bound to a datasource. One of the properties is a ClientID which I want to use to link from the ListView items to another page. In global.asax I have defined a route:
System.Web.Routing.RouteTable.Routes.MapPageRoute("ClientRoute",
"MyClientPage/{ClientID}", "~/Client.aspx");
so that for instance http://server/MyClientPage/2 is a valid URL if ClientID=2 exists.
In the ListView items I have an asp:HyperLink so that I can create the link:
<asp:HyperLink ID="HyperLinkClient" runat="server"
NavigateUrl='<%# "~/MyClientPage/"+Eval("ClientID") %>' >
Go to Client details
</asp:HyperLink>
Although this works I would prefer to use the RouteName instead of the hardcoded route by using a RouteUrl expression. For instance with a constant ClientID=2 I could write:
<asp:HyperLink ID="HyperLinkClient" runat="server"
NavigateUrl="<%$ RouteUrl:ClientID=2,RouteName=ClientRoute %>" >
Go to Client details
</asp:HyperLink>
Now I am wondering if I can combine the route expression syntax and the databinding syntax. Basically I like to replace the constant 2 above by <%# Eval("ClientID") %>. But doing this in a naive way...
<asp:HyperLink ID="HyperLinkClient" runat="server"
NavigateUrl='<%$ RouteUrl:ClientID=<%# Eval("ClientID") %>,RouteName=ClientRoute %>' >
Go to Client details
</asp:HyperLink>
... does not work: <%# Eval("ClientID") %> is not evaluated but considered as a string. Playing around with several flavors of quotation marks also didn't help so far (Parser errors in most cases).
Question: Is it possible at all what I am trying to achieve here? And if yes, what's the correct way?
Thank you in advance!
Use System.Web.UI.Control.GetRouteUrl:
VB:
<asp:HyperLink ID="HyperLinkClient" runat="server"
NavigateUrl='<%# GetRouteUrl("ClientRoute", New With {.ClientID = Eval("ClientID")}) %>' >
Go to Client details
</asp:HyperLink>
C#:
<asp:HyperLink ID="HyperLinkClient" runat="server"
NavigateUrl='<%# GetRouteUrl("ClientRoute", new {ClientID = Eval("ClientID")}) %>' >
Go to Client details
</asp:HyperLink>
I know it's basically the same as Samu Lan's solution but instead of using .net controls you could use regular HTML anchor control.
<a href='<%# GetRouteUrl("ClientRoute", new {ClientID = Eval("ClientID")}) %>'>
Go to Client details
</a>

Totally lost – data binding expressions inside GridView’s template

1) On aspx page we define GridView control named gvwPolls, and inside its template we define a user control named pollBox1
<asp:GridView ID="GridView1" DataSourceID="objPolls" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
Question is : <%# Eval("QuestionText") %> <br />
<mb:PollBox ID="PollBox1" runat="server" PollID='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="objPolls" ...></asp:ObjectDataSource>
a) I assume that inside gvwPolls’s template, the gvwPollBox1.DataBind is called before PollID='<%# Eval("ID") %>' and <%# Eval("QuestionText") %> expressions get evaluated?!
b) Can someone offer some explanation how or why is gvwPollBox1.DataBind called before PollID='<%# Eval("ID") %>' and <%# Eval("QuestionText") %> expressions get evaluated?
2) Continuing with the above example:
-- pollBox1 user control defines a Repeater control named rptOptions:
<asp:Repeater runat="server" ID="rptOptions">
<ItemTemplate>
<%# Eval("pollBoxTitle") %>
</ItemTemplate>
</asp:Repeater>
-- In pollBox1’s code-behind file we bind rptOptions to a data source inside DoBinding() method.
-- We also override pollBox1’s DataBind() method:
public override void DataBind()
{
base.DataBind();
DoBinding();
}
a) I assume that due to overriding pollBox1.DataBind(), the data binding expression <%# Eval("pollBoxTitle") %> ( defined inside rptOptions’s template ) will get evaluated prior to a call to DoBinding method? If so, won’t then <%# Eval("pollBoxTitle") %> get evaluated before rptOptions is actually bound to a data source?
b) If that is the case, how then is rptOptions able to extract value ( from data source’s pollBoxtitle property) from a data source, if at the time the <%# Eval("pollBoxTitle") %>
expression got evaluated, rptOptions wasn’t yet bound to any data source?
thanx
I can't explain why the page life cycle is the way that is, probably has something to do with rendering childs before the parent object. When exactly do you call .DataBind() in the PollBox control? Try to move it into an event that is later in the life cycle, like PreRender.
There is also another way to ensure it is working the way you want to:
Subscribe to the RowDataBound Event, use .FindControl("YourPollBoxID") to get the instance of the control current bound row, set the properties and perform a manuall .DataBind();

How do I set the Visible attribute in an ItemTemplate?

<asp:TemplateField HeaderText="Audio">
<ItemTemplate>
<asp:Image ID="playImage" runat="server"
ImageUrl="~/images/nextpg.gif"
Visible='<%# (Eval("available")=="Y") ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
In my query I am returning the "available" column which is populated with a letter of Y or N. For some reason the evaluation of this expression is never true. If I change it to != instead of == it will always be true. That leads me to believe the Eval("available")=="Y" is simply not evaluating as expected.
After much messing around, this finally worked:
<%# ((String)Eval("available")).Equals("Y") ? true : false %>
The issue seems to be that you can't use == but instead you must use the String.Equals() method. I'm not sure why but that's just the way it is.

Resources