Databind Function to Controls Visible Property Does Not Work - asp.net

I'm using databinding to set the visible property on a control as such:
Control on Page:
<asp:LinkButton ID="ApproveTimeLink" runat="server" Visible="<%# CanApprove() %>"> Approve Time</asp:LinkButton>
Code on CodeBehind:
Protected bool CanApprove()
{
return false;
}
As you can see the control should not show, yet still does. I'm not getting any errors, and I'm baffled as to why this does not work.
Thanks for the help.

all you have to this is the following
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
public bool CanApprove()
{
return false;
}
then you can use this method on the asp-control as you mentioned before!
but be we aware! Every property of the page has to be not null, otherwise the databind will fail with an exception!

Sometimes you cannot set control properties with <%# %> and you have to resort to using OnItemDataBound(...) to get a reference to the control and set its Visible property there. Another thing that sometimes can be an issue is nested quotes, but in your sample code I don't see that as a problem. If your real code includes nested quotes, like Visible="<%# CanApprove(Eval("ID"))%>" then that may be your real issue. You can get around this by using single quotes and alternating with double quotes.

This worked great for me too... thanks!!
<asp:Label runat="server" ID="lblLocaton" Text='<%# String.Format("{0}, {1}", Eval("City"), Eval("Region.Code")) %>' Visible="<%# ShowLocation() %>" />
AND
MfnPresenter.Website.Presenters.IInstituitonListView.ShowLocation
Get
End Get
Set(ByVal value As Boolean)
'Used by visibility binding expression on lblLocation control inside dlFinancialInsitution
End Set
End Property

Related

ASP.Net AjaxControlToolkit CalendarExtender not updating Textbox in code behind

Have the following:
<asp:TextBox ID="txtStart" runat="server" Enabled="false"></asp:TextBox>
<asp:Image ID="ibDateS" runat="server" ImageUrl="../SystemImages/calendar.gif" ToolTip="Click to show calendar" AlternateText="Click to show calendar" CssClass="showpointer" />
<ajaxToolkit:CalendarExtender ID="ceStart" PopupButtonID="ibDateS" Format="dd/MM/yyyy" TargetControlID="txtStart" runat="server"></ajaxToolkit:CalendarExtender>
It all works ok on the DOM and the textbox gets updated with the new date BUT when I try to get the value in code behind i.e. txtStart.Text it still has the original value set on Page_Load.
Have I missed something?
EDIT:
TextBox set originally in Page_Load (yes contained in if(!IsPostback)):
txtStart.Text = DateTime.Now.ToString("dd/MM/yyyy");
Get it later like so:
DateTime dtStart = Convert.ToDateTime(txtStart.Text);
After a bit of research apparently its an issue with setting the textbox to readonly or enabled="false" on the page. Removing this and adding the following to page_load solved the problem:
txtStart.Attributes.Add("readonly", "readonly");
if you haven't use Page.IsPostBack property of page then plz use it and try to use you pageload code inside that. It seems that it may be the problem of Page.IsPostBack,Try for that
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Your code for databind...
}
}
Hope you understand and works for you..
Enabled false preventing it to post the latest value.

Asp.NET Font-Size and service function

i've the following code in aspx page
<asp:Label ID="CittaLabel" runat="server" Text='<%# Eval("Citta") %>' Font-Size='<%# ReturnFontSize(Eval("Big")) %>'/>
and this is my code behind service function
Protected Function ReturnFontSize(ByVal Big As Boolean) As FontUnit
If Big Then
ReturnFontSize = FontSize.Medium
Else
ReturnFontSize = FontSize.Small
End If
End Function
But i get always a font very very small.
So my question is : for changing "Font-Size" proprety of a control, from code behind, which return type i have to use, assuming that FontUnit not work ?
Thank you
You have to DataBind the Containercontrol of the label(f.e. a GridView or the complete page). Then you can call a Codebehind Function from the aspx-page.
Hence f.e. in Page-Load:
Me.DataBind()
and the function must return an object from type FontSize:
Protected Function ReturnFontSize(ByVal fontSize As Object) As FontSize
Select Case fontSize.ToString.ToUpper
Case "BIG"
Return WebControls.FontSize.Large
Case Else
Return WebControls.FontSize.Medium
End Select
End Function
and on aspx-page:
Font-Size='<%# ReturnFontSize(Eval("Big")) %>'
But why dont you set the Fontsize in Codebehind on Page.Load?
Me.CittaLabel.FontSize= ....
I find that performing Eval based property setting during a databinding event can often prove problematic unless you are binding to simple types such as strings and ints. It's generally easier and to simply perform your complex binding tasks during the code behind implementation of binding events such as the Repeater databind event.
Try the following instead, assuming you are using an ASP:Repeater control:
Markup:
<asp:Repeater runat="server" ID="rpt" OnDataBinding="rpt_OnDataBinding">
<ItemTemplate>
<asp:Label ID="CittaLabel" runat="server" Text='<%# Eval("Citta") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void rpt_DataBinding(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var data = (YourTypeThatIsDataBound)e.Item.DataItem;
var CittaLabel = (Label)e.Item.FindControl("CittaLabel");
CittaLabel.FontSize = ReturnFontSize(data.Big);
}
}
This way for every item being generated in your repeater you access the label in the server side databinding event and simply set the FontSize to be the output of your ReturnFontSize function that you have alread written. The only thing you have to do is cast the e.Item.DataItem object back to the original type of object the repeater was bound to and then pass its Big property into the function.

How to use ASP.NET <%= tags in server control attributes?

This works:
<span value="<%= this.Text %>" />
This doesn't work:
<asp:Label Text="<%= this.Text %>" runat="server" />
Why is that?
How can I make the second case work properly, i.e., set the label's text to the value of the "Text" variable?
Use Data binding expressions
<asp:Label ID="Label1" runat="server" Text="<%# DateTime.Now %>" ></asp:Label>
Code behind,
protected void Page_Load(object sender, EventArgs e){
DataBind();
}
you can do this
<asp:Label ID="Label1" runat="server" ><%= variable%></asp:Label>
You will need to set the value of the server control in code
First of all, assign an ID to the label control so you can access the control
<asp:Label ID="myLabel" runat="server" />
Then, in your Page_Load function, set the value of your labels 'Text' field
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
This function will be in your code behind file, or, if you are not using the code behind model, inside your aspx page you will need
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
</script>
Good luck.
In my code i am using something like this easily but in the databound control like ListView Item template
<asp:HyperLink ID="EditAction" class="actionLinks" Visible='<%#Eval("IsTrue").ToString() != "True"%>' runat="server" NavigateUrl='<%# Eval("ContentId","/articles/edit.aspx?articleid={0}")%>' />
But when i tried to use outside the databound control using <%# .. %>, it simply doesn't work.
You can easily do with
My href
But for server controls, and outside of databound control. We need to call DataBind() in pageload event explicitly
<asp:Hyperlink ID="aa" NavigateUrl='<%#myHref%>' >
Not sure how to mark this as such, but this is a bit of a duplicate. See this thread.
I don't think embedding code in to your markup will really make your markup any clearer or more elegant.
<asp:Label> is compiling at runtime and converting to html tags. You can set text with codebehind or like this:
<asp:Label id="Text1" runat="server" />
<% Text1.Text = this.Text;%>
UPD: Seems like my variant doesnt work, this is better:
protected void Page_Load(object sender,EventArgs e)
{
Text1.Text = this.Text;
}
Just pitching this little nugget in for those who want a good technical breakdown of the issue -- https://blogs.msdn.microsoft.com/dancre/2007/02/13/the-difference-between-and-in-asp-net/
I think the crux is in pretty decent agreement with the other answers:
The <%= expressions are evaluated at render time
The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
<%# expressions can be used as properties in server-side controls. <%= expressions cannot.

ASP.NET linkbutton visible property issue

I'm using a public variable called IsAdmin in the code behind of an aspx page.
public partial class _news : System.Web.UI.Page
{
public bool IsAdmin = false;
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.Name.Contains("admin"))
{
IsAdmin = true;
}
else
{
IsAdmin = false;
}
}
And i use the property Visible='<%#IsAdmin%>' to assign to panels which i want to show if the user is an admin in the aspx design of the page. Strangely it works for the linkbuttons i've put on the repeater.
<asp:Panel ID="Panel1" runat="server" Visible='<%#IsAdmin%>'>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl='<%# "news_edit.aspx? Action=edit&id=" + Convert.ToString( Eval("news_id")) %>Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" PostBackUrl='<%# "news.aspx?Action=delete&id=" + Convert.ToString( Eval("news_id")) %>'>Delete</asp:LinkButton>
</asp:Panel>
and it works fine, however outside the repeater i've put another linkbutton without a panel
<asp:LinkButton ID="LinkButton4" runat="server" PostBackUrl="~/news_edit.aspx?action=new" Visible='<%#IsAdmin%>'>Add New Item</asp:LinkButton>
but the visible property doesn't work on it! I tried putting it inside a panel too and setting it's visible property but that too didn't work.
So i have following doubts
1)what is the issue?
2)what is the technical name when we use references like '<%#IsAdmin%>' in the design page
3)Does page load happen before page is rendered of after page is rendered?
Thanks
<%# %> is the syntax used for accessing databound fields. Since you are likely databinding the Repeater control at some point, these expressions will be evaluated.
Since you are likely not calling databind on the Panel and the Linkbuttons outside of the Repeater, these expressions will not be processed. You can probably change them to something like
<%= IsAdmin.ToString() %>
and get the result you want.
Check this great blog entry for more information on the differences.
Also, Page Load happens before the page is rendered. Rendering the page is the last thing that happens in the ASP.Net page lifecycle.

Assigning Visible Property of the Button to a Static Method Result

I am trying to hide the button based on the user's role using the following code:
<asp:Button ID="btndisplayrole" Text="Admin Button" Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' runat="server" OnClick="DisplayRoleClick" />
But when I run the above code I get the following error message:
Cannot create an object of type 'System.Boolean' from its string representation '<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' for the 'Visible'
Kind of an interesting issue.. But as the error message states, the string <%= WebApplication1.SiteHelper.IsUserInRole("Admin") %> cannot be converted to a boolean.
Unfortunately i cannot explain why the expression isn't evaluated, but instead is treated like a string.
The reason why your <%# %> expression works as expected, is because it is treated much differently. When the Page is compiled into a class, then the compiler creates an event handler similar to this:
public void __DataBindingButton2(object sender, EventArgs e)
{
Button button = (Button) sender;
Page bindingContainer = (Page) button.BindingContainer;
button.Visible = HttpContext.Current.User.IsInRole("admin");
}
and hooks this method up to the Control.Databinding event on your control. As you can see, the <%# %> is this time properly treated as server code, and not just a random string.
So i guess the solution is either to use databinding, or go to the codebehind as AndreasKnudsen suggests.
As an alternative solution:
<% if (WebApplication1.SiteHelper.IsUserInRole("Admin"))
{%>
<asp:Button ID="btndisplayrole"
Text="Admin Button"
runat="server"
OnClick="DisplayRoleClick" />
<%} %>
The following code worked:
Visible='<%# WebApplication1.SiteHelper.IsUserInRole("Admin") %>'
Note that the aboe use the binding expression!
how about just doing it in the codebehind, for instance on Page_Load ?
public void Page_Load( object sender, EventArgs e )
{
btndisplayrole.Visible = WebApplication1.SiteHelper.IsUserInRole("Admin");
}
Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin").ToString() %>'
OR
Visible=<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>

Resources