Embedded Code in attribute of asp.net controls - asp.net

I want bind the visibility of a panel to the selectedValue Or selectedIndex of a gridview, so i try this:
<asp:Panel ID="pnlPic" Visible='<% gvAllQuarries.SelectedIndex == -1 ? false:true %>' runat="server" >
or
<asp:Panel ID="pnlPic" Visible='<%= gvAllQuarries.SelectedIndex == -1 ? false:true %>' runat="server" >
but syntax is wrong and unknown for intelisense. how can i bind like this? is it possible?

Try putting an event handler on the SelectedIndexChanged event of the GridView; you can then show/hide the panel accordingly: (VB.NET)
Protected Sub gvAllQuarries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles gvAllQuarries.SelectedIndexChanged
pnlPic.Visible = Not (gvAllQuarries.SelectedIndex = -1)
End Sub
Mess around with the logic to get it playing how you want, adapt to C# if need be.
As an alternative you can wrap the panel in a conditional block if you want it all inline:
VB.NET:
<% If gvAllQuarries.SelectedIndex <> 1 Then%>
<asp:Panel ID="Panel1" runat="server">
//put whatever inside the panel
</asp:Panel>
<% End If %>
C#:
<% if (gvAllQuarries.SelectedIndex != 1) { %>
<asp:Panel ID="Panel1" runat="server">
//put whatever inside the panel
</asp:Panel>
<% } %>
It's a bit messy, but the only way I can see of you getting it all inline without code-behind. The option you are trying Visible='<% gvAllQuarries.SelectedIndex == -1 ? false:true %>' will only work if you use data-binding syntax ('<%# %>'), and then you will need to explicitly call DataBind() on it from code-behind anyway.
Unfortunately using '<%= $>' will just output static text and not be evaluated into a boolean to apply to the visible property.
Adapted from this similar question.

Related

Using c# in Web Forms to passing parameter to user control

From an aspx page, I am trying to display a user control for each item in a collection, but the C# seems to be ignored when tryign to set the UserControl parameter:
<%foreach (Fetus item in this.pregnancy.Fetus) {%>
//this returns a GUID:
"<%= item.Id.ToString() %>"
//this does not work, returns the characters between "" like < %= item.Id.ToString()%>:
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId="<%= item.Id.ToString()%>" />
<% } %>
I would expect this to work, what's wrong?
You have to use a data binding expression
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# item.Id.ToString()%>' />
But you have to call DataBind() in code behind for that to work.
You can also use a Repeater
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# Eval("id").ToString()%>' />
</ItemTemplate>
</asp:Repeater>
And then bind data to it in code behind
Repeater1.DataSource = pregnancy.Fetus;
Repeater1.DataBind();

using values within if conditions in mark up

I want to use a value that is pulled from the SQL within the if statement. Ideally i want to do the equivalent of
<% If DataBinder.Eval(Container, "DataItem.BookID") == 1 Then%>
Is there a way to do this with the correct syntax?
This is how you put conditions in aspx file. Just a rough sample base on what I understand:
<%# System.Convert.ToInt32((DataBinder.Eval(Container.DataItem, "BookID")!="") ? DataBinder.Eval(Container.DataItem, "BookID"):0) %>
Make sure you have int in BookID not any other type.
Explaining Further:
In case you want to have an if else condition:
<%# If DataBinder.Eval(Container.DataItem, "DATAFIELD") <> "" Then
Response.Write("something")
End If %> // This is invalid
The above statement can be properly written in aspx file as this:
<%# DataBinder.Eval(Container.DataItem, "DataField").Equals("")?"":"Something"%>
I'm not sure if this can be done or not the way you are requesting it.
As you may or may not know, the typical way to do this is to have a control in your markup, like so
<asp:listView ID="SophiesListView" ...
..
<ItemTemplate>
<asp:HyperLink ID="hlGlossary" title="click here for more information" target="_blank" runat="server" />
</ItemTemplate>
</asp:listView />
Then, in the codebehind, find your listview / repeater / datagrid or what have you and choose ItemDataBound. Inside this event, do something like this:
If e.Item.DataItem("vehicleType") IsNot DBNull.Value AndAlso e.Item.DataItem("vehicleType") = "JETSKI" Then
DirectCast(e.Item.FindControl("hlGlossary"), HyperLink).NavigateUrl = "Glossary.aspx#JETSKI"
DirectCast(e.Item.FindControl("hlGlossary"), HyperLink).Text = "?"
End If
To keep your page logic as simple as possible your best bet is to data bind to the Visible property of controls. For example, if you want to only show some html if the BookID == 1 then create a new property on your data source like this
public bool Show
{
get
{
return BookID == 1;
}
}
and in your page you'd have
<asp:Placeholder runat="server" Visible='<%# Eval("Show") %>'>
...html goes here...
</asp:Placeholder>

Call method in ListView EmptyDataTemplate

I have a simple ListView with an EmptyDataTemplate. In the EmptyDataTemplate, there is a LinkButton whose Visble property value is an expression that calls a method in my code behind. The problem is that the LinkButton is always visible regardless of whether the method returns true or false (my method isn't being called as I even set a breakpoint on it). Anyone come across this? What's happening here?
e.g.
<asp:ListView ID="peopleListView" runat="server" ...>
...
<EmptyDataTemplate>
Sorry, no people to view.<br />
<asp:LinkButton ID="newButton" runat="server" Visible='<%# EditPermitted() %>'>New Record</asp:LinkButton>
</EmptyDataTemplate>
</asp:ListView>
In the code behind, I have the method:
protected bool EditPermitted()
{
return false;
}
I don't think you can put scriplets <% %> inside of server controls.
You need to grab the RowDataBound event, and set the link button's visibility there
void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.EmptyDataRow) {
LinkButton lb = e.Row.FindControl("newButton");
lb.Visible = EditPErmitted();
}
}
You can't use code blocks like <% ... %> or <%= ... %> inside the attributes of server controls. Only data binding blocks like <%# ... %>. But you can use code blocks inside your EmptyDataTemplate, in this case a simple if statement should work:
<EmptyDataTemplate>
<% if(EditPermitted()) { %>
<asp:LinkButton ID="newButton" runat="server" ... />
<% } %>
</EmptyDataTemplate>

asp.net, enable/disable tabpanel

Why isn't this working?
<ajaxToolkit:TabPanel Enabled='<%# User.IsInRole("admin") %>'...
While this works:
<asp:TextBox Enabled='<%# User.IsInRole("admin") %>'...
Is the first example within a binding context (bound control)? Perhaps you want to use the output directive instead of the binding directive?
<ajaxToolkit:TabPanel Enabled='<%= User.IsInRole("admin") %>'
EDIT: My bad. <%= %> translates into Response.Write, which is not what you want -- too used to ASP.NET MVC, I guess. The best thing is to make it runat="server", give it an ID and set the value in your code-behind.
<ajaxToolkit:TabPanel runat="server" ID="myTabs" ... />
protected void Page_Load( object sender, EventArgs e )
{
myTabs.Enabled = User.IsInRole("admin");
...
}

Dynamically adding controls in ASP.NET Repeater

I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.
I cannot seem to find an easyway to essentially do the following:
if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text")
<asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
else
<asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work
In your repeater, drop a Panel, then create an event handler for the repeater's data binding event and programmatically create the TextBox or CheckBox and add it as a child control of the Panel. You should be able to get the DataItem from the event args to get information like your "type" attribute or values to feed your Text properties or css information, etc.
I would go with mspmsp's sugestion. Here is a quick and dirty code as an example of it:
Place this in your aspx:
<asp:Repeater ID="myRepeater" runat="server" OnItemCreated="myRepeater_ItemCreated">
<ItemTemplate>
<asp:PlaceHolder ID="myPlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
</ItemTemplate>
</asp:Repeater>
And this in your codebehind:
dim plh as placeholder
dim uc as usercontrol
protected sub myRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
if TypeOf e Is ListItemType.Item Or TypeOf e Is ListItemType.AlternatingItem Then
plh = ctype(e.item.findcontrol("myPlaceHolder1"), Placeholder)
uc = Page.LoadControl("~/usercontrols/myUserControl.ascx")
plh.controls.add(uc)
end if
end sub
What about something similar to this in your markup in each the textbox and checkbox controls?
Visible=<%= Eval("type").tostring() == "text") %>
If there is needed to add controls based on data then there can be used this approach:
<asp:Repeater ID="ItemsRepeater" runat="server" OnItemDataBound="ItemRepeater_ItemDataBound">
<itemtemplate>
<div>
<asp:PlaceHolder ID="ItemControlPlaceholder" runat="server"></asp:PlaceHolder>
</div>
</itemtemplate>
</asp:Repeater>
protected void ItemRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var placeholder = e.Item.FindControl("ItemControlPlaceholder") as PlaceHolder;
var col = (ItemData)e.Item.DataItem;
placeholder.Controls.Add(new HiddenField { Value = col.Name });
placeholder.Controls.Add(CreateControl(col));
}

Resources