Using c# in Web Forms to passing parameter to user control - asp.net

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();

Related

Passing CommandArguement to LinkButton from variable

I have seen many resources on SO that say that I can use following syntax to pass value to CommandArguement of `LinkButton'
<%forearch(var comment in Comments){%>
<asp:LinkButton ID="del" CommandArguement='<%= comment.CommentId%>' onCommand="delete_click" Text="Delete"/>
<%}%>
But when I write this in my ascx file and click on the link the value passed to command argument is "<%=comment.CommentId%>" instead of commentId itself. Please guide what am I doing wrong?
Edit 1
based on answers and comments, I have moved to use repeater instead of foreach and plain code. Here is the code I have come up with
<asp:Repeater ID="commRepeater" SelectMethod="GetPageComments" runat="server">
<ItemTemplate>
<p>
<%#Eval("Comment") %>
<%if(Page.User.Identity.IsAuthenticated && Page.User.Identity.GetUserId() == Eval("UserId")){ %>
<span>
<asp:LinkButton Text="Edit" runat="server" ID="EditLink" CommandArgument='<%#Eval("CommentId")%>' OnClick="Update_Comment" />
<asp:LinkButton Text="Delete" runat="server" ID="DeleteLink" CommandArgument='<%#Eval("CommentId")%>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" OnCommand="Delete_Comment" />
</span>
<%} %>
</p>
</ItemTemplate> </asp:Repeater>
you can see that I am trying to show the edit and delete links if user is logged in and his Id matches with user who commented but it tells me that I can on use Eval in databound controls. how would I hide/show edit/delete links conditionally within repeater
You could simply use codebehind, for example in Page_Load:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
del.CommandArgument = comment.CommentId;
}
}
Maybe a better approach would be to use the Comments-collection(which seems to be a list or array of a custom class) as DataSource of a Repeater(or other web-databound control). Then you can add the LinkButtons to the Itemtemplate.
You can then either use ItemCreated or ItemDataBound events of the repeater in codebehind or inline ASP.NET tags to bind the CommandArgument.
For example:
CommandArguement='<%# DataBinder.Eval( Container.DataItem, "CommentId" ) %>'
What you are doing currently is not recommended and is highly error prone. You can easily achieve this with ASP.NET Repeater control like this:-
<asp:Repeater ID="MyRepeater" runat="server">
<ItemTemplate>
<asp:LinkButton ID="del" CommandArguement='<%# Eval("CommentId") %>'
OnCommand="del_Command" Text="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
In Page_Load simply bind it:-
if (!Page.IsPostBack)
{
MyRepeater.DataSource = CommentsRepository();
MyRepeater.DataBind();
}
Or Else if you are have ASP.NET 4.5 then use strongly type Data Bound controls like this:-
<asp:Repeater ID="MyRepeater" runat="server" ItemType="MyNamespace.Comment"
SelectMethod="MyRepeater_GetData">
<ItemTemplate>
<asp:LinkButton ID="del" CommandArguement='<%# Item.CommentId %>'
OnCommand="del_Command" Text="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
And you method in code behind should be something like this(just for Demo):-
public IEnumerable<MyNamespace.Comment> MyRepeater_GetData()
{
return new List<Comment>
{
new Comment { CommentId =1, Name= "foo"},
new Comment { CommentId =2, Name= "bar"},
};
}

ASP.NET Linkbutton not getting dynamic value for commandargument value

<%
foreach (training t in traininglist)
{
%>
<tr>
<td><%=t.TrainingId%></td>
<td><%=t.TrainingName%></td>
<td>
<asp:LinkButton runat="server" ID="EditBtn"
Text="Edit" OnCommand="editbtn_OnCommand"
CommandArgument='<%# t.TrainingId %>' CommandName="edit" />
</td>
</tr>
<% } %>
where,
training is the class and traininglist is List<training> defined in Page_Load() function in codebehind.
I am trying to call the
public void editbtn_OnCommand(object sender, CommandEventArgs e)
{
String myeid = e.CommandArgument.ToString();
....
}
Here, myeid is not getting value but always shows <%# t.TrainingId %>
i have already tried all other options like <%: t.TrainingId %> or <%=t.TrainingId %>
The output of Tag "<%= %>" is more likely similar to use Response.Write in your code. so these tags are used to display the value to the response object.
That's why,as per my understanding, You can't used these tags to set commandargument property of controls unless you are using DataBinding. If you are using DataBinding then these tags "<%= %>" are used to set the property of controls.
Because you are here looping through each item in list on html table, my suggestion is to use GridView or Repeater and then Bind through your List Object. if you are using this way, you can get rid of unwanted formatting issues of html tables also.
Refer http://msdn.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
If you want to use repeater then you can use these specific tags, and this should be your code(not actual code, just sample one)
<asp:Repeater id="myRepeater" runat="server" >
<ItemTemplate>
<div>
<asp:LinkButton runat="server" id="EditBtn" CommandName="edit"
CommandArgument="<%#Container.DataItem.TrainingId %>" Text="Edit"
OnCommand="editbtn_OnCommand" />
</div>
</ItemTemplate>
</asp:Repeater>

UserControl not loading in ListView

I've create my own UserControl called 'ReevooBadge' and have placed it in my listview by registering my UserControl. However, my UserControl isn't visible in the ListView. Any sugestions for this problem?
This is my User Control
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ReevooBadge.ascx.cs" Inherits="KiaEurope2010.Website.controls.Addons.Widgets.ReevooBadge" %>
<a class="reevoomark <%= this.ClassName %>" href="//mark.reevoo.com/partner/<%= this.CountryCode %>/series:<%= this.SelectionIdentifier %>"><%= this.ReviewsTitle %></a>
I need to implement this in my ListView by the following code implementation
<asp:ListView ID="lvItemCarousel" ItemPlaceholderID="carrouselitems"OnItemDataBound="lvItemCarousel_ItemDataBound"
runat="server">
<layouttemplate>
<asp:PlaceHolder ID="carrouselitems" runat="server" />
</layouttemplate>
<itemtemplate>
<li>
<asp:HyperLink runat="server" ID="hlItem">
<asp:Image runat="server" ID="imItem" />
<div class="modelTitle">
<asp:PlaceHolder runat="server" ID="phReevoo" Visible="false">
<rhm:ReevooBadge runat="server" ID="ReevooBadge" />
</asp:PlaceHolder>
</div>
</asp:HyperLink>
</li>
</itemtemplate>
</asp:ListView>
Above I register my custom User Control
<%# Register Src="~/controls/Addons/Widgets/ReevooBadge.ascx" TagPrefix="rhm" TagName="ReevooBadge" %>
And in the Item Data Binding
protected void lvItemCarousel_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//...
phReevoo.Visible = true;
ReevooBadge.ModelItem = this.Item;
ReevooBadge.CountryCode = KiaEurope.SitecoreLayer.Reevoo.Settings.GetReevooKey(LanguageCountryCultureHelper.CurrentCountryCode, Sitecore.Context.Language);
}
However, the user control isn't visible in the ListView.
I'm not sure how you're getting your code to compile because I couldn't reference phReevoo (the placeholder control) directly in the ItemDataBound event.
I needed to use the following:
e.Item.FindControl("phReevoo").Visible = true;
The same would apply if you tried to reference ReevooBadge.
To make the testing easier I created a web user control and used this as a substitute for your custom user control. After binding to a simple List<string>, the control showed without issue.
I would suggest checking if your user control is actually rendering outside of the ListView.

ASP.NET Dropdrownlist croaks with SelectValue Assignment

This is my aspx
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ObjectDataSource ID="DSCategories" runat="server"
SelectMethod="GetCategories" TypeName="BAL.CategoryBAL">
</asp:ObjectDataSource>
<div id="Criteria">
<h3>Category:</h3>
<asp:DropDownList ID="ddlCategories" runat="server"
DataSourceID="DSCategories" DataTextField="Description"
DataValueField="Code">
</asp:DropDownList>
<asp:Button ID="btnSetCriteria" runat="server" Text="Set Criteria" />
</div>
</asp:Content>
And this is briefly my Page_Load code:
SearchCriteriaBAL scb = SearchCriteriaBAL.GetSearchCriteria(id);
string cat = String.Empty;
if (!string.IsNullOrEmpty(scb.Criteria))
{
cat = ParseCriteria(scb.Criteria);
ddlCategories.SelectedValue = cat;
}
I break on the SelectedValue assignment line and see the items in the dropdownlist and I see a valid value for cat and it is in the list but I get:
'ddlCategories' has a SelectedValue
which is invalid because it does not
exist in the list of items. Parameter
name: value
It seems to be doing the GetCategories AFTER I set the selectedValue and then it dies.
I placed it on its own test page for fear of interaction but it still fails. Has anyone seen this before?
You could try selecting the item this way:
ddlCategories.Items.FindByValue(cat).Selected = true;
Which of course wont' work if cat really isn't in the Items collection
Write the function on DropDownList's DataBound event instead of Page_Load
Occurs after the server control binds
to a data source.
<asp:DropDownList ID="ddlCategories" runat="server"
DataSourceID="DSCategories"
DataTextField="Description"
DataValueField="Code"
OnDataBound="ddlCategories_DataBound">
</asp:DropDownList>
Rather than using SelectedValue, I would have opted
ddlCategories.Items.FindByValue(cat.Trim()).Selected = true;

Tuncate string in ASP.NET using VB.NET

I made a function to truncate a string in the code behind file. But how do i use it in the aspx file?
This is the textbox:
<asp:TemplateField HeaderText="page" HeaderStyle-Wrap="true">
<ItemTemplate>
<a href='<%# makepageURL( Eval("page") )%> '>
<%# Eval("page")%>
</a>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpage" TextMode="SingleLine" Rows="1" Width="100%" runat="server" Text='<% #Bind("page") %>' />
</EditItemTemplate>
</asp:TemplateField>
And this is my function:
Public Function TrimString(ByVal Value As String, ByVal Length As Integer) As String
If Value.Length > 20 Then
Return Value.Substring(Value.Length - (20 - 3)) + "..."
End If
Return Value
End Function
It's not an issue of how to use it, but actually when to use it?
If you had a regular span, you could do this:
<span><%: TrimString("somestring") %></span>
But this is a TextBox your dealing with (user input).
When should it truncate?
On Form Submit? (that would make sense).
As they type (well then you'd need to use JavaScript).
By the looks of your code snipper, your using a FormView.
So i wouldn't be calling it from the ASPX (which the equivalent of executing code during Page Render), i would be calling it during the Edit/Submit event, server-side event handler.
In other words, truncate the value the user put in, after they have submitted the form and before you persist to the database.

Resources