casting problem of star rating? - asp.net

I have an application with ajax star rating but when i am assigning value to CurrentRating from datatable then it showing error of "Specified cast is not valid".
I am using this code.
<asp:TemplateField HeaderText="Rating" SortExpression="CustomerRating">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "CustomerRating")%>'></asp:Label></a>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:Rating ID="Rating1" runat="server" CurrentRating='<%# Bind("CustomerRating") %>'
StarCssClass="ratingStar"
WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar"
EmptyStarCssClass="emptyRatingStar"
>
</cc1:Rating>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
Then its showing error CurrentRating='<%# Bind("CustomerRating") %>'.
I am taking refrence from these sites.
asp.net forum
Code Project
Same thing working on Code project.

The problem is most likely that the CustomerRating property of your data item is not of the correct data type. Rating expects an int. The Databinder does use reflection and attempts to automatically handle type conversions, but it has limits.
Unfortunatly there isn't enough information in your qustion to know what the actual runtime type of CustomerRating is, so I can't say why it can't be cast. My advise would be to explicitly cast or convert the property like so:
CurrentRating='<%# (string)Bind("CustomerRating") %>'
CurrentRating='<%# Bind("CustomerRating").ToString() %>'
CurrentRating='<%# (int)Bind("CustomerRating") %>'
If you can't convert it simply, or just need to get a debugger on it so you can figure out what the type is you can call out to a custom method in your code-behind instead (and you can attach a debugger there to so you can see the runtime type of the item:
CurrentRating='<%# MyCustomMethod(Eval("CustomerRating")) %>'
in code behind:
public string MyCustomMethod(object customerRating)
{
string rValue = ... //do whatever you need to do to customerRating to get a string out of it
// good place to set a breakpoint you you can examine what type customerRating actually is so you can figure out how best to convert it to something databinding can use
return rValue;
}

Related

error message "String was not recognized as a valid Boolean" in aspx page

I have a SQL stored proc where I am creating a column ("Certified") dynamically based on two other columns. The value from this column is a '0' or '1'. The SQL stored proc query is:
, CASE WHEN
(StartMiles < EndMiles)
AND (StartTime < EndTime)
AND (bcd.Status != 'C')
THEN '1' ELSE '0' END
AS Certified
On the front end in my aspx page, I have a telerik radgrid that will display a checkbox (enabled if value is 1, disabled if value is 0). The aspx code is:
<telerik:GridTemplateColumn DataField="Certified" HeaderText="Certified" Visible="true">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox2_CheckedChanged"
Enabled='<%# !bool.Parse(Eval("Certified").ToString()) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
I am getting an error on the aspx page String was not recognized as a valid Boolean
To resolve the error, how can I set a datatype in the stored proc?
<telerik:GridTemplateColumn DataField="Certified" HeaderText="Certified" Visible="true">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox2_CheckedChanged"
Enabled='<%# !Convert.ToBoolean(Convert.ToInt32(Eval("Certified").ToString())) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
I would recommend using a code-behind method to do this instead of putting logic into the markup via embedded code blocks, like this:
Markup:
<telerik:GridTemplateColumn DataField="Certified" HeaderText="Certified"
Visible="true">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true"
OnCheckedChanged="CheckBox2_CheckedChanged"
Enabled='<%# IsCertified(Eval("Certified").ToString()) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
Code-behind:
protected bool IsCertified(string certifiedValue)
{
return !bool.Parse(certifiedValue);
}
Note: To be safer, I would recommend using the Boolean.TryParse() method instead of just the Parse(), as that will eliminate the chance of a string that cannot be parsed into a bool from throwing an exception. Read Boolean.TryParse Method documentation for more information.
This provides two advantages, in my opinion, over the OP code:
Simplified markup, because you do not have conditional logic in the markup, but now just a call to the method.
You can leverage the power of Visual Studio's IntelliSense, compiler to catch syntax errors at compile-time instead of run-time and the debugger itself.

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>

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.

asp.net databinding string is passed to function but runtime occurs

I'm using a code-behind function (called TestFx) in my binding expression. I'm passing a string and the function accepts a string but I still get a runtime error saying invalid args.
But if I change the method to accept an object and inspect the value, "it's a string!"
Can someone please explain?
-rod
ProductDescription:
<asp:Label ID="ProductDescriptionLabel" runat="server"
Text='<%# TestFx(Eval("ProductDescription")) %>' />
<br />
Another option is to handle repeater control ItemDataBound event. It's more suitable if ItemTemplate elements require complex decoration
The return type of Eval is object. As you've noticed, you can either change the signature of your method to accept an object, or you can typecast the result of Eval("ProductDescription") to a string:
<asp:Label ID="ProductDescriptionLabel" runat="server"
Text='<%# TestFx(Eval("ProductDescription").ToString()) %>' />

Formatting DataBinder.Eval data

How can I format data coming from a DataBinder.Eval statement in an ASPX page?
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
The code for this goes like this:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?
There is an optional overload for DataBinder.Eval to supply formatting:
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
http://msdn.microsoft.com/en-us/library/3d2sz789.aspx
You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.
You also can format your field inline:
<%# ((DateTime)DataBinder.Eval(Container.DataItem,"publishedDate")).ToString("yyyy-MMM-dd") %>
If you use ASP.NET 2.0 or newer you can write this as below:
<%# ((DateTime)Eval("publishedDate")).ToString("yyyy-MMM-dd") %>
Another option is to bind the value to label at OnItemDataBound event.
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
To format the date using the local date format use:
<%#((DateTime)Eval("ExpDate")).ToString("d")%>
How to Format an Eval Statement to Display a Date using Date Locale
Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.
Mark Up:-
<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>
Code behind:-
Public Function fLabel(ByVal tval) As String
fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>
You can use it this way in aspx page
<%# DataBinder.Eval(Container.DataItem, "DateColoumnName", "{0:dd-MMM-yyyy}") %>

Resources