asp:DataList control with asp:LinkButton inside - something's weird - asp.net

I'm working through examples in a book trying to learn ASP.NET, and I've stumbled on something strange in there. First of all, if I type it as it's written in the book, VS gives me errors. This is the code as it's written in the book:
<asp:DataList ID="employeesList" runat="server">
<ItemTemplate>
<asp:Literal ID="extraDetailsLiteral" runat="server" EnableViewState="false" />
Name: <strong><%#Eval("Name") %></strong><br />
Username: <strong><%#Eval("Username") %></strong><br />
<asp:LinkButton ID="detailsButton" runat="server" Text=<%#"View more details about " + Eval("Name")%>
CommandName="MoreDetailsPlease"
CommandArgument=<%#Eval("EmployeeID")%> />
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:DataList>
So, I've plucked at it for a while, and came up with this solution which actually compiles:
<asp:DataList ID="employeesList" runat="server" onitemcommand="employeesList_ItemCommand">
<ItemTemplate>
<asp:Literal ID="extraDetailsLiteral" runat="server" EnableViewState="false" />
Name: <strong><%#Eval("Name") %></strong><br />
Username: <strong><%#Eval("Username") %></strong><br />
<asp:LinkButton ID="detailsButton" runat="server" Text='View more details about <%# Eval("Name") %>'
CommandName="MoreDetailsPlease" CommandArgument='<%Eval("EmployeeID") %>' />
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:DataList>
Notice that I've also added the OnItemCommand in the asp:DataList tag, so now I'm able to fire the event as expected.
However, results in the browser isn't what I expect; the Name and Username listed in strong text show just fine, but the Literal control that should show extra details (the EmployeeID field) and the Name field inside the LinkButton won't show their values in the page:
not showing as expected http://lh6.ggpht.com/_x84bQLYH57A/SgxzygartcI/AAAAAAAAAIY/nhT-6RUJa6o/s144/EmployeeDirectory_notshowing.jpg
It should say "EmployeeID: 1" and "View more details about Zak Ruvalcaba"
I guess it's the Eval function that's not working when inside another control, can anyone help me out?

Change the LinkButton as :
<asp:LinkButton ID="detailsButton" runat="server"
Text='<%# Eval("Name", "View more details about {0}") %>'
CommandName="MoreDetailsPlease"
CommandArgument='<%# Eval("EmployeeID") %>' />
Sorry I confused the order of parameters. I updated my answer. Format must be the second parameter.

You can view another question I posted yesterday concerning something eerily similar here:
Need help with Eval inside DataList
I do believe Canavar actually gave the correct answer, however.

Related

ASP.NET Repeater FindControl not working for Label, but works for Textbox

I'm facing issues trying to get controls from my repeater. I have one label and one textbox. The label is giving me a null reference error, however the textbox is working.
Markup:
<asp:Repeater ID="PalletsRepeater" runat="server" OnItemDataBound="PalletsRepeater_ItemDataBound">
<ItemTemplate>
<div style="margin-left: 20px; margin-top: 5px;">
<asp:Label lbl="lblPalletId" Text='<%#"Pallet "+Eval("PALLETID")%>' runat="server" />
<asp:Label Text=", Qty = " CssClass="field-label-blue" runat="server" />
<asp:TextBox ID="txtPalletItemQty" runat="server" Text='<%# Eval("ITEMQTY") %>' step="1" type="number" />
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
foreach (RepeaterItem repeaterRow in PalletsRepeater.Items)
{
// This fails.
string palletId = ((System.Web.UI.WebControls.Label)repeaterRow.FindControl("lblPalletId")).Text;
// This works.
string palletItemQty = ((System.Web.UI.WebControls.TextBox)repeaterRow.FindControl("txtPalletItemQty")).Text;
}
I have researched this on Stack Overflow and most answers involve using the OnItemDatabound event, but when I tried to implement those answers, it still comes back null for the label. Personally I don't understand the suggestions as far as using the OnItemDatabound event.
Change
<asp:Label lbl="lblPalletId" Text='<%#"Pallet "+Eval("PALLETID")%>' runat="server" />
Into
<asp:Label id="lblPalletId" Text='<%#"Pallet "+Eval("PALLETID")%>' runat="server" />
You cannot find it because it has no ID

Image not getting displayed in datalist

I am binding images to datalist. Taking the image name from database and giving the path.
My code is:
<asp:DataList ID="dlImages" runat="server" RepeatColumns="4">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%# Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
On .cs page:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
dlImages.DataSource = ds.Tables(0)
dlImages.DataBind()
I am facing 2 problems :
When imagename has space in between it adds %20 in between
Eg. if imagename is "API Message", it takes it as: "API%20Message"
I tried On this Problem:
Added ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg"))'
But I got error:
XML literals and XML properties are not supported in embedded code within ASP.NET
If there is not space Eg.image name is "Charges" , Then also its not showing it in datalist.
When i ran project, and right clicked on it and view source, then its showing me correct path as:
src="D:\Sagar\Kinston\WebSite\ScreenMasterImages\Charges.jpg"
but not showing image.
Please help me with above code.
Where i have made mistake?
What else i should add in it?
Keep it easy and simple.
When trying things like that with URL, to know exactly what to write down, try typing it in your address bar so you'll be able to find the exact syntax needed in order to make it work correctly.
I've done this tons of time and work for me... So you could try something like :
<asp:DataList ID="dlImages" runat="server" RepeatColumns="4">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
ImageUrl='<%# String.Format("{0}{1}.jpg", "~\ScreenMasterImages\", Server.HtmlDecode(Eval("PageName"))) %>'
runat="server" />
</ItemTemplate>
</asp:DataList>

My modal window is not transferring values to vb.net codebehind

I am getting the username and password to run some scripts
<act:ModalPopupExtender ID="unixLoginMPE" runat="server" TargetControlID="rdoUnix"
PopupControlID="unixPanel" BackgroundCssClass="modalBackground" CancelControlID="unixCancel" OkControlID="unixSubmit"
/>
<asp:Panel ID="unixPanel" runat="server"
CssClass="modalPopup" align="center" Style="display: none">Unix Username: <asp:TextBox ID="unixName" ClientIDMode="Static" runat="server" />
<br />
Unix Password: <asp:TextBox ID="unixPass" runat="server" ClientIDMode="Static" TextMode="Password" />
<br />
<asp:Button ID="unixCancel" runat="server" Text="Cancel" />
<asp:Button ID="unixSubmit" ClientIDMode="Static" runat="server" Text="Submit" OnClientClick="enableRDO()" />
</asp:Panel>
In my codebehind, I'm doing something like this just to test if the values have passed.
Dim UNIXPASSWORD As String = unixPass.text
Dim UNIXUSERNAME As String = unixName.Text
MsgBox(UNIXCOMPUTERNAME)
MsgBox(UNIXUSERNAME)
MsgBox(UNIXPASSWORD)
I do reference a script to enable the radio button. I asked a question to help me with that issue, it is all resolved Radio Button won't stay check if I have a modal window open up when it is selected
<script type="text/javascript">
function enableRDO() {
var cancel = document.getElementById('rdoUnix');
cancel.setAttribute('checked', 'true');
};
</script>
For some reason the values are passing just fine in Google Chrome but not in IE. I've been at this for a few hours and don't know what else to try...or search for
EDIT:
I'm still trying to attempt this. I setup up dummy text boxes which I will hide later on if I can pass to them. I'm still very lost with this...
<asp:TextBox ID="dummyUnixName" runat="server" />
<asp:TextBox ID="dummyUnixPass" runat="server" />
If you aren't performing a postback or an AJAX call, nothing will be passed to the code behind.
During debugging, Console.WriteLine can be redirected to the output window in VS; in production, it's going to go nowhere. A logging solution is often appropriate for a web application which needs to know more of what happened than which page was requested by a user (IIS logs).

force user select from autocomplete

i am beginner for asp.net . I now facing a problem . How can i force a user to select option from ajax control toolkit autocomplete?
Here is my sample code
<cus:cusTextBox ID="txtCMemberID" runat="server" Action="Edit"
CssClass="inputTextM" OnTextChanged="txtCMemberID_TextChanged"
AutoPostBack="True"></cus:cusTextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
ServicePath="~/Module/Common/autoComplete/acLewreMember.asmx"
MinimumPrefixLength="1" ServiceMethod="GetSuggestedStrings"
TargetControlID="txtCMemberID" CompletionInterval="10"
CompletionSetCount="3" EnableCaching="true"
CompletionListCssClass="completionListElement"
CompletionListItemCssClass="listItem"
CompletionListHighlightedItemCssClass="highlightedListItem"
FirstRowSelected="True"
ShowOnlyCurrentWordInCompletionListItem="True">
</asp:AutoCompleteExtender>
As you see the textbox is a custom control. Is that any way to force user to select option from autocomplete?Please provide me a sample code also. thanks
ASP.NET includes a useful feature called a validator.
<asp:TextBox ID="TextBox2" ValidationGroup="Group2" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ErrorMessage="*Required" ValidationGroup="Group2"
ControlToValidate="TextBox2" runat="server" />
<asp:Button ID="Button2" Text="Validate Group2"
ValidationGroup="Group2" runat="server" />
Here is the resource link for msdn: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx
I'm not sure how these work with custom controls as I'm relatively new at asp. They also have a custom validator which might be more suited for your purposes, but like I said. I don't know exactly.
Note: If the client is using an old browser this won't work, so you also want to check on the server that this field isn't empty by using:
if (Page.IsValid)
{
//stuff to do in your event handler
}

ASP.NET How to pass container value as javascript argument

I am using an oBout Grid control with a template on a textbox.
I would like to pass an argument to a javascript, the current row index of a grid when a user clicks on it.
But the result of
onClick='setGridInEditMode(<%# Container.RecordIndex %>);' />
comes out as
onClick="setGridInEditMode(<%# Container.RecordIndex %>);"
Is there a way to pass container value to javascript?
Here is the markup in question.
<cc1:Grid ID="_TrustGrid" runat="server"
FolderStyle="Styles/style_7"
AllowAddingRecords="False"
AllowSorting="false"
AllowPageSizeSelection="False"
AllowPaging="False"
AllowMultiRecordEditing="true"
AutoGenerateColumns="False"
OnUpdatecommand="_TrustGrid_UpdateCommand"
OnRebind="_TrustGrid_Rebind">
<Columns>
<cc1:Column AllowEdit="true" AllowDelete="false" HeaderText="Edit" Width="130" runat="server" />
<cc1:Column DataField="TrustDocID" HeaderText="TrustDocID" Width="125" ReadOnly="false" AllowDelete="false" TemplateId="trustDocIDGridTemplate" />
</Columns>
<Templates>
<cc1:GridTemplate ID="trustDocIDGridTemplate" ControlID="tb1" runat="server">
<Template>
<asp:TextBox ID="trustDocIDTextBox" runat="server"
Visible="true"
Text='<%# Container.Value %>'
onClick= 'setGridInEditMode(<%# Container.RecordIndex %>);' />
</Template>
</cc1:GridTemplate>
</Templates>
</cc1:Grid>
I'd second Darin's call for using unobtrusive JavaScript. However, that doesn't answer your question on why ASP.NET is doing this.
The reason you get
onClick="setGridInEditMode(<%# Container.RecordIndex %>);"
is because databinding to server control properties requires you to bind directly to the property without intervening text. That means, only Property="<%# ... %>" is allowed.
So in your case, you'll need to say what you want in a roundabout fashion (although I personally think this is a little clearer and more maintainable):
onClick='<%# String.Format("setGridInEditMode({0});", Container.RecordIndex) %>'
(Watch your single and double quotes though!)
This limitation applies only to server controls and their properties. It does not apply to a server control's nested literal content (such as bodies of templates or panels) nor to plain HTML used elsewhere, which is probably why you've never noticed this before.
Instead of polluting your HTML with javascript functions how about an unobtrusive solution using jQuery:
$(function() {
$('#_TrustGrid input[id*=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
setGridInEditMode(index);
});
});
});
If you prefer instead the more ASP.NETish solution you could always do this:
<asp:TextBox
ID="trustDocIDTextBox"
runat="server"
Visible="true"
Text='<%# Container.Value %>'
onclick='<%# "setGridInEditMode(" + Container.RecordIndex + ")" %>' />

Resources