This might be a problem with Session and not ToString(), I'm not sure.
I have two .aspx pages and I want to pass an IP address from a datatable from one page to the other. When I do this, spaces get added that I don't want. The simple version of the code is this:
first .aspx page
int num = DropDownList1.SelectedIndex;
DataView tempDV = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2];
Response.Redirect("test.aspx");
test.aspx page
string ipCamAdd = Session["camera"].ToString();
TextBox1.Text = "http://" + ipCamAdd + "/jpg/image.jpg?resolution=320x240";
what I want to print is
http ://ipadd/jpg/image.jpg?resolution=320x240
but what prints out is
http//ipaddress /jpg/image.jpg?resolution=320x240
how can I fix this?
Also, I asked this question hoping someone could tell me why this is happening as well. Sorry for the mistake.
Try this:
string ipCamAdd = Session["camera"].Trim().ToString();
For the valid concern, Session["camera"] could be null, add function such as the following to your code
static string ToSafeString(string theVal)
{
string theAns;
theAns = (theVal==null ? "" : theVal);
return theAns;
}
Then use:
string ipCamAdd = Session["camera"].ToSafeString().Trim();
You can use string.Replace if you just want to get rid of the spaces:
TextBox1.Text = "http://" + (ipCamAdd ?? "").Replace(" ", "") + "/jpg/image.jpg?resolution=320x240";
Trim the result before setting to session.
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2].Trim();
Seems In SQL your data type is char(*) if you convert the data type to varchar and re enter data, you wont get any additional spaces
Related
I added a function to my application recently that reads a date from a downloaded file and finds the difference in days between current date and the date from the file. When done, it is displayed in a label in one of my forums.
There is an exception: if the string in the file equals "Lifetime", it should not process it as a date and follow alternate logic. But when I try to check if the string is "Lifetime", it does not return true, even if the string = "Lifetime".
EDIT: I fixed the FormatException with help from Nisarg. Now, my labels aren't changing to the values. This is the problem.
EDIT2: I feel stupid. I found out that I was initiating Main twice in one function, then using main1 to switch between forms and main to set the labels.
This is why the labels weren't working right. Thanks Nisarg and all other contributors.
Code example:
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
if (subScript == "Lifetime") // it bypasses this, apparently blank
{
main.daysLeftLabel.Text = "Expires: Never";
}
if (subScript != "Lifetime") //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString(((Convert.ToDateTime(subScript)) - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
While using files you often get trailing blank spaces or newline characters. Try trimming the string before comparing it to Lifetime:
subScript = subScript.Trim().Trim(Environment.NewLine.ToCharArray());
Another (less likely) problem could be with the comparison itself. In C# the comparison in case-sensitive. So if you're comparing lifetime with Lifetime they are considered unequal. You should rather use case-insensitive comparison:
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
OR
if(subScript.ToLower() == "lifetime")
You could also check if the subScript you are getting from the file is a valid date or not using DateTime.TryParse.
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
DateTime subScriptDate;
if(!DateTime.TryParse(subScript, out subScriptDate))
{
main.daysLeftLabel.Text = "Expires: Never";
}
else //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString((subScriptDate - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
I think it is because main is the starting point of a program in C#, make another methodname if you donĀ“t want it to reset things from where the program is supposed to start from
That is my guess only, make a breakpoint in the beginning of your code and check through what info you get from each row in the code
Almost certainly, the actual content of the string is not actually the string "Lifetime". Probably because of white-space on either side. Try trimming.
Relevant edit:
if (subscript.Trim() == "Lifetime")
{
main.daysLeftLabel.Text = "Expires: Never";
}
else // don't retest for the opposite condition
{
...
As you can see, this thing is awfully fragile, because the string could still be many things that aren't a valid DateTime. Smells like homework, but there you go...
i think you should use
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
{
//statement
}
else
{
//statement
}
I have a bunch of string which i loop through . I want to insert an apostrophe when ever an apostrophe in any string that has apostrophe. I simply do something like below.
string strStatus = "l'oreal";
index = strStatus.IndexOf("'");
strStatus.Insert(index, " ' ");
I want to have output like l''oreal. Yet this fails. I tried using escape patter
strStatus.Insert(index, " \' ");
All to no avail. Please how do i achieve this? Any suggestion/help is highly appreciated.
Strings are immutable. Insert returns a new string with the 2 apostrophes, it doesn't modify strStatus in any way. Your code simply discards the result of Insert.
You should try:
string strStatus = "l'oreal";
index = strStatus.IndexOf("'");
string newStatus=strStatus.Insert(index, "'");
Strings are immutable in .NET (and Java), which means Insert does not modify strStatus, instead it will return a new instance which has the modification you're after.
Do this:
String status = "L'Oreal";
status = status.Insert( status.IndexOf('\''), "'" );
Strings are immutable in C#, so all it's methods do not modify the string itself - they return modified copy. This should work:
strStatus = strStatus.Insert(index, " ' ");
I have image tag in my html like img src="/images/image.jpg".
I want it like src="mydomain.com/images/image.jpg"
So I want to replace all src="/ to src="mydomain.com/.
I tried this
string repto = "src=\"/" + strLink.HRef + "/";
strEncode.Replace("src=\"/", repto);
strEncode contains my html.
I tried many ways but nothing is working. Please help, if any body has any idea about this.
Thanks
string foo = #"src=\"/images/image.jpg\"";
string bar = foo.Replace("src=\"", "src=\"mydomain.com");
Maybe
html_string.Replace("src=\"/images", "src=\"mydomain.com/images");
?
String#Replace does not change the value of strEncode, in fact it returns a new string with the encoded value.
So this may help you out:
strEncode = strEncode.Replace("src=\"/", repto);
I take data from four different pages and different domains.
1- .com
2- .co.uk
3- .ca
4- .co.jp
For all of the above i take number from Html and Convert them to Double using line:
string lowestSellerPrice = (Convert.ToDouble(fbalPrice) +
Convert.ToDouble(fbalsPrice)).ToString();
This works perfectly fine for the first 3 domains but for .co.jp even though there is always a number in fbalPrice and fbalsPrice it is always giving exception :
Input string was not in a correct format
Any suggestion as i have been struggling with this for too long now no result i also tried the try parse solution but no luck.
UPDATE:
See this:
I solved it like this :
The string were like " 1234" and " 111" and i then did Replace(" ",""); . And only number lift this however did not work so i did this:
if (fbalPrice.Contains(" "))
{
fbalPrice = fbalPrice.Remove(0, fbalPrice.IndexOf(" ") + 1).Replace(",","").Trim();
}
if(fbalsPrice.Contains(" "))
{
fbalsPrice = fbalsPrice.Remove(0, fbalsPrice.IndexOf(" ") + 1).Replace(",", "").Trim();
}
And then added them and it worked.
I have created the yahoo weather API app using ASP.Net MVC 3 and when I tried to insert the postcode to the text field to find the correct xml, I wanted to leave gap for the standard UK postcode. Can you please help me to do that. The following code's model.PostCode represents the PostCode variable which has declared as string in model. This code is in the controller file.
private Boolean LookupWeather(ref RssModels model)
{
string WoeidUrl = "http://where.yahooapis.com/v1/places.q('" +
model.PostCode +
"')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";
XDocument getWoeid = XDocument.Load(WoeidUrl);
try
{
model.Woied = (int)(from place in getWoeid.Descendants("place")
select place.Element("woeid")).FirstOrDefault();
return true;
}
catch
{
return false;
}
If you can please help me to get the URL like follows.
http://where.yahooapis.com/v1/places.q('mk10%202hn')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--
Thank you in advance.
Use UrlEncode
string WoeidUrl = "http://where.yahooapis.com/v1/places.q('"
+ UrlEncode(postCode)
+ "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";
All the browser is doing for that is replacing the space with %20, you can replicate this just by using Replace, try:
string postCode = model.PostCode.Replace(" ", "%20");
Then use it in your code above like so:
string WoeidUrl = "http://where.yahooapis.com/v1/places.q('"
+ postCode
+ "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";