Basically in my in my aspx page I have a gridview which displays the value from my database as an image. So if a value in my database table is 5, it will be displayed as 5 images in the gridview. ie.(star.jpg star.jpg star.jpg star.jpg star.jpg)
The code:
Protected Function getrating(ByVal rate As Integer)
Dim getrating As String
getrating = ""
For i = 1 To rate
getrating = getrating + "<img src=""Images/star.jpg"" alt=""*"">"
Next
Return getrating
End Function
It's been working fine so far for whole numbers, but now I'm adding averages into my database, so any value with a decimal point(like 4.6) gives me the error
"Conversion from type 'DBNull' to type 'Integer' is not valid."
How would I go about in adding images when the value has a decimal point?
Since the field in my database has the range set to numbers 1 to 5, I like it to display another image if the value has a decimal point. ie. "3.5" would display in the gridview star.jpg, star.jpg, star.jpg, halfstar.jpg. If that made any sense lol.
Anyone have an idea on how to do doing this?
Judging by your error, it's probable that you're not even accepting decimal values and inserting the NULL value when they occur. Fix that first, make sure the result isn't DBNull, then you can make the changes to a decimal type like Double:
Protected Function GetRating(ByVal rating As Double) As String
Dim result As New System.Text.StringBuilder()
While rating >= 1.0#
result.Append("<img src=""Images/star.jpg"" alt=""*"">")
rating -= 1.0#
End While
If rating > 0.0# Then _
result.Append("<img src=""Images/halfstar.jpg"" alt=""1/2"">")
Return result.ToString()
End Function
I also took the liberty of using a StringBuilder instead of concatenating strings with +.
You need to check DBNull value (From error description).
If reader.Read() Then
IF Not reader.IsDBNull(0) Then '1st column
'If field type is decimal
Dim decimalVar=reader.GetDecimal(0)
End If
End If
If you want to do this I really recommend to use one image which contains all stars in it. So that image should have 5 Stats like:
For this demo I added a image with 120px width and 24px height. Then You need to add a like this:
Then when you want to show your stars, you need to find out the width of this with following method:
DIV width = (Rate/5) * 120
So for example 2.5 will be (2.5/5)*120 = 60! Then you need to change DIV's width to 60 and then you'll have your 2.5 rank! and will become something like:
<div style="background-image:url(http://s.codeproject.com/script/Ratings/Images/stars-fill.png);width:60px;height:24px;">
</div>
This is just a simple method which will give you an idea to expand and customize for your logic. I hope this helps :-)
Live Demo: http://jsfiddle.net/qxrub/
Related
So I am going off memory here because I cannot see the code I am trying to figure this out for at the moment, but I am working with some old VB Script code where there is a data connection that is set like this:
set objCommand = Server.CreateObject("ADODB.command")
and I have a field from the database that is being stored in a variable like this:
Items = RsData(“Item”).
This specific field in the database is a long string of
text:
(i.e. “This is part of a string of text…Header One: Here is text after header one… Header Two: Here is more text after header two”).
There are certain parts of the text that I wish to store as a variable that are between two index positions in the long string of text within that field. They are separated by headers that are stored in the text field above like this: “Header One:” and “Header Two:”, and I want to capture all text that occurs in between those two headers of text and store them into their own variable (i.e. “Here is text after header one…”).
How do I achieve this? I have tried to use the InStr method to set the index but from how I understand how this works it will only count the beginning of where a specific part of the string occurs. Am I wrong in my thinking of this? Since that is the case, I am also having trouble getting the Mid function to work. Can some one please show me an example of how this is supposed to work? Remember, I am only going off of memory so please forgive me that I am unable to provide better code examples now. I hope my question makes sense!
I am hopeful that someone can help me with an answer tonight so I can try this out tomorrow when I am near the code again! Thank you for your efforts and any help offered!
You can extract all the substrings starting with the text Header and ending just before either the next Header or end-of-string. I have used regular expression to implement that and it is working for me. Have a look at the code below. If I get a simpler(non-regex solution), I will update the answer.
Code:
strTest = "Header One: Some random text Header Two: Some more text Header One: Some random textwerwerwefvxcf234234 Header Three: Some more t2345fsdfext Header Four: Some randsdfsdf3w42343om text Header Five: Some more text 123213"
set objReg = new Regexp
objReg.Global = true
objReg.IgnoreCase = false
objReg.pattern = "Header[^:]+:([\s\S]*?)(?=Header|$)" '<---Regex Pattern. Explained later.
set objMatches = objReg.Execute(strTest)
Dim arrHeaderValues() '<-----This array contains all the required values
i=-1
for each objMatch in objMatches
i = i+1
Redim Preserve arrHeaderValues(i)
arrHeaderValues(i) = objMatch.subMatches.item(0) '<---item(0) indicates the 1st group of each match
next
'Displaying the array values
for i=0 to ubound(arrHeaderValues)
msgbox arrHeaderValues(i)
next
set objReg = Nothing
Regex Explanation:
Header - matches Header literally
[^:]+: - matches 1+ occurrences of any character that is not a :. This is then followed by matching a :. So far, keeping the above 2 points in mind, we have matched strings like Header One:, Header Two:, Header blabla123: etc. Now, whatever comes after this match is relevant to us. So we will capture that inside a Group as shown in the next breakup.
([\s\S]*?)(?=Header|$) - matches and captures everything(including newlines) until either the next Header or the end-of-the-string(represented by $)
([\s\S]*?) - matches 0+ occurrences of any character and capture the whole match in Group 1
(?=Header|$) - match and capture the above thing until another instance of the string Header or end of the string
Click for Regex Demo
Alternative Solution(non-regex):
strTest = "Header One: Some random text Header Two: Some more text Header One: Some random textwerwerwefvxcf234234 Header Three: Some more t2345fsdfext Header Four: Some randsdfsdf3w42343om text Header Five: Some more text 123213"
arrTemp = split(strTest,"Header") 'Split using the text Header
j=-1
Dim arrHeaderValues()
for i=0 to ubound(arrTemp)
strTemp = arrTemp(i)
intTemp = instr(1,strTemp,":") 'Find the position of : in each array value
if(intTemp>0) then
j = j+1
Redim preserve arrHeaderValues(j)
arrHeaderValues(j) = mid(strTemp,intTemp+1) 'Store the desired value in array
end if
next
'Displaying the array values
for i=0 to ubound(arrHeaderValues)
msgbox arrHeaderValues(i)
next
If you don't want to store the values in an array, you can use Execute statement to create variables with different names during run-time and store the values in them. See this and this for reference.
I have an asp.net 4 textbox control that has it's text being dynamically populated by some java script. A Google Maps call to be exact. It's giving me mileage from 1 point to another. When the text displays, it shows " 234 mi" I need to get rid of the "mi" part of this text because the text is being converted to an Int32 Updating a table in my DB.
Basically I can only have an INT. Nothing else in the text box. How do I get rid of the "mi" at the end of the text?
Thanks
C#
EB
On the postback, before you save it you could:
var saveValue = Int32.Parse(tbTarget.Text.Replace("mi", string.Empty).Trim());
If your working with a variable length of chars (say someone enters miles instead) then your must do a foreach against the string (an array of char) and check isnumeric on each char.
A simple String.Substring works also:
String leftPart = TxtMileAge.Text.Substring(0, txt.IndexOf(' '));
int mileAge = int.Parse(leftPart);
This retrieves the part of the String in the range of 0 - indexOfWhiteSpace and converts it to an int
Edit: Since the value can have decimal places (as you've commented), you need to parse it to double, round it and then cast it to int:
var txtEstDistance = new TextBox() { Text = "40.2 mi" };
String leftPart = txtEstDistance.Text.Substring(0, txtEstDistance.Text.IndexOf(' '));
double distanceMiles = double.Parse(leftPart, System.Globalization.CultureInfo.InvariantCulture);
int oDdstanceMiles = (int)Math.Round(distanceMiles, MidpointRounding.AwayFromZero);
In my aspx page I have a gridview which displays the value from my database as "*". So if a value in my database table is 5, it will be displayed as "*****" in the gridview.
code in aspx:
<asp:TemplateField HeaderText="Rating" SortExpression="Rating">
<ItemTemplate><h1><%# getrating(Eval("Rating"))%></h1></ItemTemplate>
</asp:TemplateField>
code in aspx.vb
Protected Function getrating(ByVal rate As Integer)
Dim retval As String
retval = ""
For i = 1 To rate
retval = retval + "*"
Next
Return retval
End Function
What I want to do is change that "*" to a picture, ie star.jpg, so in the gridview it will display the image star.jpg instead of "*".
Any idea on how to do this please? Using MS visual studio 2010
You should be able to just do something like the following:
retval = retval + "<img src=""star.jpg"" alt=""*"">"
You may need some styling to put them all on the same line (float:left should do) but I forget offhand whether that is necessary.
The principle of this is obviously pretty basic. In the outputted HTML you will just have an image tag where before you had a *. A neater way to do it might be to have five images for one to five and then have something like:
Protected Function getrating(ByVal rate As Integer)
Dim retval As String
retval = String.Format("<img src=""Star{0}.jpg"" alt=""{0} stars"">", rate)
Return retval
End Function
This will output an image tag pointing to any of Star1 to Star5. This is nicer in some ways because it allows better control over how they look as well as allowing you to make five identical sized images and know that the space used will always be the same.
Here's an implementation using CSS - http://www.thebroth.com/blog/119/css-rating-stars - does require additional divs and two images to create effect but seems to be a neat solution.
I have a quick question about JQuery. I have dynamically generated paragraphs with id's that are incremented. I would like to take information from that page and bring it to my main page. Unfortunately I am unable to read the dynamically generated paragraph IDs to get the values. I am trying this:
var Name = ((data).find("#Name" + id).text());
The ASP.NET code goes like this:
Dim intI As Integer = 0
For Each Item As cItem in alProducts1
Dim pName As New System.Web.UI.HtmlControls.HtmlGenericControl("p")
pName.id = "Name" & intI.toString() pName.InnerText = Item.Name controls.Add(pName) intI += 1
Next
Those name values are the values I want...Name1, name2, name3 and I want to get them individually to put in their own textbox... I'm taking the values from the ASP.NET webpage and putting them into an AJAX page.
Your question is not clear about your exact requirement but you can get the IDs of elements with attr method of jQuery, here is an example:
alert($('selector').attr('id'));
You want to select all the elements with the incrementing ids, right?
// this will select all the elements
// which id starts with 'Name'
(data).find("[id^=Name]")
Thanks for the help everyone. I found the solution today however:
var Name = ($(data).find('#Name' + id.toString()).text());
I forgot the .toString() part and that seems to have made the difference.
I would like to know the easiest way to format a string as accounting style. I know how to format as currency using {0:c} but there are some differences in accounting style, for example, all the dollar signs will line up as well as all the decimal points, and negatives are expressed in parenthesis rather than with a "-" minus sign. You can find a good example of the way i would like it in excel if you format the cells as "accounting" with 2 decimal places.
Ignoring your alignment requirements, you could use
number.ToString("€#,##0.00;(€#,##0.00);Zero")
to bracket negative numbers.
To align your numbers, you'd have to format without the currency symbol, and pad the formatted numbers yourself with spaces, using a fixed width font would make this job easier for you.
EDIT:
It seems String.Format is your friend:
String.Format("{0,15:#,##0.00 ;(#,##0.00);- }", number)
where 15 is the total width of the output, and you need to append this text to your currency symbol. (Again, this aligns in fixed width only)
There's no format string shortcut (the single-character ones with default rules) for handling accounting style formats (here's a cheat sheet with the available format strings) so you'll have to write a more specific one (like Patrick's answer) or your own parsing method.
The alignment requirements would be specific to how you're displaying them. I'm assuming you are using a table, in which case you're limited by what HTML supports, and it doesn't support accounting style alignments like Excel.
In this blog there were some various formats outlined and this one seemed to be close to what you were looking for:
int neg = -10;
int pos = 10;
// C or c (Currency): It represent how many decimal place of zeros to show.
String.Format("{0:C4}", pos); //"$10.0000"
String.Format("{0:C4}", neg); //"($10.0000)"
It doesn't handle the padding (you may have to fix that yourself), but it does have the proper parenthesis.
You could do something using a variation of Patricks method. This will handle formating and alignment assuming you know the upper bound of how large a value you are dealing with:
private static string OutputAsCur(decimal val)
{
string format = " #,##0.00 ; (#,##0.00);Zero";
string frmt = val.ToString(format);
return CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + frmt.PadLeft(15, ' ');
}
Here's a simple example app to see it format:
static void Main(string[] args)
{
decimal d = 155.55m;
Console.WriteLine(OutputAsCur(d));
Console.WriteLine(OutputAsCur(d * -1));
Console.WriteLine(OutputAsCur(1002.32m));
Console.WriteLine(OutputAsCur(1002.32m * -1));
Console.ReadLine();
}
You can use a format string for String.Format to get what you're trying to accomplish. The only trick is that positive numbers, since they will not have a closing parenthesis mark, will have to incorporate a space at the end if they will be aligned with any negative numbers that will be in the column. The trick is to get that space into the string in a way that HTML will not ignore. I simply use the HTML entity which indicates a non-breaking space in HTML.
Here's sample code. First, in the aspx.
<table>
...
<tr>
<th scope="row" colspan="2">Total Revenue</th>
<td class="numeric total"><asp:Label runat="server" ID="TotalRevenueLabel" /></td>
</tr>
...
</table>
Now, the codebehind.
public const string kMoneyFormat = "#,#.00' ';(#,#.00);'-.-- '";
public void DataBind()
{
using (FinancialDataContext sql = new FinancialDataContext())
{
var periodQuery = from m in sql.Forecasts()
select m;
ForecastsResult periodData = periodQuery.Single();
decimal totalRevenue = period.Data.income_actual.Value + periodData.other_income.Value;
TotalRevenueLabel.Text = totalRevenue.ToString(kMoneyFormat);
}
}
I followed these steps for apply the "Accounting" format.
In a new Book on Excel, select a cell.
Insert data (i.e any number; for this example, add 80000).
Select (Accounting) NumberFormat as is shown in the screenshot #1:
Screenshot #1:
Select "More Number Formats".
Select "Custom".
Select any of the pre-defined formulas (see screenshot #2).
Screenshot #2:
In my case, this is the desired format for this number.
The negative side of this is that when you select the cell with the format applied on it, you wont see selected (Accounting) "in the DropDownList" Number Format.