Is it possible to use DataBinding to evaluate Controls on .aspx page? - asp.net

I'm not sure if I am asking this question correctly. I know that I can accomplish what I need in code behind, but I'm wondering if this is possible. I want to hide a control if there is a value in another control. I know I can use databinder.eval in a repeater, but can I use it just for a normal asp control on the page?
In other words, I want to do something like this:
<asp:TextBox runat="server" ID="ConditionalText" Text="Show if other value is empty" Visible ='<%# testValue.Text != "" ? false : true %>'></asp:TextBox>
<asp:TextBox runat="server" ID="testValue"></asp:TextBox>
I tried just the way I have it above, and <%# testValue. exposed available properties of "testValue" TextBox so I thought it might work. It didn't throw any errors but it did not show/hide the textbox. I'm just wondering if this is possible and what I would have to do to accomplish this.
Any assistance is greatly appreciated.

It can work, but since you are using a databinding expression outside a GridView, Repeater etc. you have to call it manually.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//rest of the code
}
//call databind manually
DataBind();
}
PS better to use IsNullOrEmpty instead of = ""
<asp:TextBox runat="server" ID="ConditionalText" Text="Show if other value is empty"
Visible='<%# !string.IsNullOrEmpty(testValue.Text) ? false : true %>'></asp:TextBox>

Related

How to hide link button based on a result returned by a class ?

I am bit new to C# and got a question.
I have a class as below that simply return false ( this is just to test)
public class SetAuthority
{
public SetAuthority()
{
//
// TODO: Add constructor logic here
//
}
public static Boolean AuthorizedToAddEdit()
{
return false;
}
}
I have a DetailsView with two link buttons to Edit and add New record. I want to hide the link buttons based on the above class method returning value.
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="New" Text="New"></asp:LinkButton>
</ItemTemplate>
Above works file and Edit and New link buttons are hidden when I run the program.
But the question is, I have a separate link button outside of the DetailsView. It is just a link to navigate to another page. I want to hide this in similar way using the same logic. I have the below code in my webform.
<asp:LinkButton ID="LinkButton5" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="OpenAdminPage" Text="Open Admin Page"></asp:LinkButton>
But the link button is always visible and seems it is not calling the class and not getting the value back. It appeared to be the class not return any value and can someone help me to identify what is the different between having this and working in DetailsView and not working for a simple link button.
Note: have a workaround where I can call the same method in Page Load event that works fine without any issue. Code is below
protected void Page_Load(object sender, EventArgs e)
{
Boolean myAllowAdd;
myAllowAdd = SetAuthority.AuthorizedToAddEdit();
if (myAllowAdd == false)
{
LinkButton1.Visible = false;
}
}
The reason is that this is for databinding expressions only: <%# Since the DetailsView is databound it works there.
If you would DataBind the page it worked also for the LinkButton outside of the DetailsView:
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
inline asp.net tags... sorting them all out (<%$, <%=, <%, <%#, etc.)
Side-note: be careful with static in ASP.NET. The static method does not yet hurt. But if you'd also use static fields you'd enter a minefield since it would be shared across all requests. Your current code-behind "work-around" is the better approach anyway.

<%# Eval("Name1.Text")%> is empty

<asp:Literal ID="Name1" runat="server">Item Name</asp:Literal>
<asp:LinkButton runat="server" EnableViewState="false" Text='<%#Eval("Name1.Text")%>' />
Why Eval() returns empty ?
Thanks.
You are able to Eval controls that were Databound. If you call Page.DataBind you can eval all controls which NamingContainer is the Page.
If you for example DataBind a Gridview, you could eval controls in GridRows.
The time you might want to pass dynamic value as command argument is when it is inside of a databound control.
If it is stand alone control you don't need to pass those values as command argument but simply access them directly inside the Click or OnCommand Event.
If the control is inside of a DataBound control you can set the Command argument in the code-behind.
You could debug it by handling the databinding event of whatever you're trying to databind and taking a look at the variable you're after in that context. Often trying to look at the variable in debug mode will make it very obvious what the problem is.
I don't think that control will be rendered in time.
Do it in code behind.
protected void Page_Init(object sender, Eventargs e)
{
lnkButtonID.Text = Name1.Text;
lnkButtonID.CommandArgument = Name1.Text;
}
In fac I would like to do this :
<asp:ImageButton runat="server" ID="addToCartIMG" OnCommand="btnAdd_Click" EnableViewState="false" CommandArgument='<%# itemId1.Value + ";" + Name1.Text %>' ImageUrl="<%$Resources:MasterPage, Image_AddToCart%>" />
where Item1 is hiddenField and Name1 a literal.
When I debug the method btnAdd_Click, the CommandEventArgs is empty.

Haw can i use a value from a session variable within the attribute of a control?

I have an ASP control custom built and I need to pass a value taken from a session variable to it like so:
<custom:control id='mycontrol' value="+Session['myControlValue']+">
...
</custom:control>
the above code obviously doesn't work, I need a way to insert the Session value in the control in this way somehow, can anyone help?
If it is a data bound control you may try this:
<custom:control id="mycontrol"
runat="server"
value='<%# Session["myControlValue"] %>'>
</custom:control>
Personally I would prefer setting this value from the code behind. It seems a little strange to me that a view (aspx) page manipulates the session:
protected void Page_Load(object sender, EventArgs e)
{
mycontrol.Value = Session["myControlValue"];
}
Switch the quotes, like so:
<custom:control id="mycontrol"
runat="server"
value='<%# Session["myControlValue"] %>' />

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.

LINQ query to WebControl.Controls

I have three TextBox controls on the page
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
OnTextChanged="TextBox_TextChanged" TabIndex="1">
<asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True"
OnTextChanged="TextBox_TextChanged" TabIndex="2">
<asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True"
OnTextChanged="TextBox_TextChanged" TabIndex="3">
and an event handler
protected void TextBox_TextChanged(object sender, EventArgs e)
{
WebControl changed_control = (WebControl)sender;
var next_controls = from WebControl control in changed_control.Parent.Controls
where control.TabIndex > changed_control.TabIndex
orderby control.TabIndex
select control;
next_controls.DefaultIfEmpty(changed_control).First().Focus();
}
The meaning of this code is to automatically select TextBox with next TabIndex after page post back (see Little JB's problem). In reality I receive InvalidCastException because it's impossible to cast from System.Web.UI.LiteralControl (WebControl.Controls contains actually LiteralControls) to System.Web.UI.WebControls.WebControl.
I am interested is it possible to modify this aproach somehow to receive working solution? Thank you!
OfType
from control in changed_control
.Parent
.Controls
.OfType<WebControl>()
You should be able to use the OfType method, to only return controls of a given type.
e.g.
var nextcontrols = from WebControl control in
Changed_control.Parent.Controls.OfType<TextBox>()... etc
The problem is that LiteralControl does not inherit from WebControl. It can't have the focus though, so it's OK to not select them. In your LINQ statement, add another condition checking for a WebControl. So your where line should be where control.TabIndex > changed_control.TabIndex && control is WebControl.

Resources