How can I add values to querystring?
I'm trying to do this:
String currurl = HttpContext.Current.Request.RawUrl;
var querystring = HttpContext.Current.Request.QueryString.ToString();
var PrintURL = currurl + (String.IsNullOrEmpty(querystring)) ?
HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty;
But I keep getting this error:
Cannot implicitly convert type 'string' to 'bool'
all i'm trying to do is get current url and add ?pring=y to querystring
Well, the first problem can be solved using this instead:
var PrintURL = currurl + (String.IsNullOrEmpty(querystring) ?
HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty);
All that's changed from your original code is simply moving the closing paren from (String.IsNullOrEmpty(querystring)) (where it was unnecessary) to the end of the ?: clause. This makes it explicitly clear what you're trying to do.
Otherwise, the compiler tries to concatenate the result of String.IsNullOrEmpty(querystring) (which is a bool) to currUrl -- incorrect, and not what you intended in the first place.
However, you've got a second problem with the HttpContext.Current.Request.QueryString.Add("print", "y") statement. This returns void, not a string. You'll need to modify this part of your ternary expression so that it returns a string -- what are you trying to do?
HttpContext.Current.Request.QueryString.Add("print", "y") returns void, not a string, so you can't use that call in the ternary expression. Plus, adding to the querystring on the Request won't affect your HTTPResponse, and I'm assuming that's what you want to do. You need to craft the new URL and use response.redirect to have the browser load the new url with the updated querystring.
i figured it out.
String currurl = HttpContext.Current.Request.Url.ToString();
String querystring = null;
// Check to make sure some query string variables
// exist and if not add some and redirect.
int iqs = currurl.IndexOf('?');
if (iqs == -1)
{
String redirecturl = currurl + "?print=y";
}
not sure if this is the cleanest way but it works.
thanks all for help
There's a couple things wrong here with what you're trying to do.
The first thing is that the QueryString collection is a NameValueCollection. The Add method has a void return. So even trying to assign the result of QueryString.Add isn't going to work.
Second, you can't modify the QueryString collection. It's read-only. There's a response over on Velocity Reviews that talks to exactly what you're trying to do. Instead of trying to modify the query string, you should redirect the user with the new value.
currurl + (String.IsNullOrEmpty(querystring)
has to return a boolean so condition has to be different.
First problem is you need brackets around your statement that is using the ?:
var PrintURL = currurl + ((String.IsNullOrEmpty(querystring)) ? HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty);
The next problem is that HttpContext.Current.Request.QueryString.Add does not return anything so one side of the : returns void where the other returns and empty string.
Related
I have a string which is getting from a userInput. What I want to do now is removing a unique character from this string but only remove it once. The main problem is that this unique character doesn't have a unique index. For example:
User has input a string like : "0123456", and now I want to remove the first '1',so the string will be output like "023456". How ever, if a user input a string like "01123456", how can I remove the first '1' and make it looks like "0123456"? I am looking for a method that can be used for both of situation. I was using string.TrimStart(), but doesn't get what I want. How can I do this?
You could use Remove and IndexOf.
var str = "01123456";
var i = str.IndexOf('1'); // IndexOf returns -1 when there is no element found, so we need to handle that when calling remove.
var res = (i >= 0) ? str.Remove(i, 1) : str;
Console.WriteLine(res); // 0123456
I think you what you need is string.Remove method. See MSDN documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=netframework-4.7.2#System_String_Remove_System_Int32_System_Int32_
If you don't know where is your character, at first call string.IndexOf to find it. If this call returns nonnegaive number, call Remove to remove it. Just note that string is immutable so it will always create a new object.
yourstring = yourstring.IndexOf('1') != -1 ? yourstring.Remove(yourstring.IndexOf('1'), 1) : yourstring;
Another way would be to use a combination of Contains, Remove, and IndexOf:
if (userInput.Contains('1')) userInput = userInput.Remove(userInput.IndexOf('1'), 1);
Or if you want to be Linq-y...
userInput = string.Concat(userInput.TakeWhile(chr => chr != '1')
.Concat(userInput.SkipWhile(chr => chr != '1').Skip(1)));
If we use the example string:
localhost:12345/MATCH_THIS_PART/more_strings
How would I return the value MATCH_THIS_PART and set it as the value of returnString. I think the problem can be solved using regex, and this is what I think would work:
string returnString = Regex.Match(Request.UrlReferrer.ToString(), #"not sure what goes here");
So basically, what goes in the part where I put
"not sure what goes here"
There are several options. String splitting is the easiest one:
string part = Request.UrlReferrer.ToString().Split('/')[1]; // gets the second item
Or use this regular expression and get the first capture:
.*?\/(.*?)\/.*
Hi i'm working on a basic windows form in c# and I have a little problem with the Trim() method.
There are 3 text boxes in witch the user enters his first name, last name and an ID.
Then he can save the info by clicking on a save button but I want to make sure that he doesn't leave blank boxes so I do the following test:
string CFN = Curator_FN.Text;
string CLN = CURATOR_LN.Text;
string CID = CURATOR_ID.Text;
Curator_FN.Text.Trim();
CURATOR_ID.Text.Trim();
CURATOR_LN.Text.Trim();
if (((Curator_FN.Text.Length == 0) || (CURATOR_ID.Text.Length == 0) || (CURATOR_LN.Text.Length == 0)))
{
MessageBox.Show("You Have to enter a First Name, a Last Name and an ID");
Empty = true;
}
The problem is if I just make some blank space with the space bar the Trim() method doesn't consider them as a blank space..
Maybe I just misunderstand the Trim() method and if I do, do you have any idea on how I could do the this?
Thanks in advance.
The Trim method does not modify the contents of the text boxes, it simply returns the trimmed version. You need to store this version, for example
Curator_FN.Text = Curator_FN.Text.Trim();
Of course this has the potential to make changes visible to the user (and it also has to access the UI thread which under other circumstances might be a problem), so it is far better to use a local variable as in
var curatorFn = Curator_FN.Text.Trim();
// etc
if (curatorFn.Length == 0 || ... ) {
// show messagebox
}
Of course if this is all you need to do, using string.IsNullOrWhiteSpace might be a more convenient alternative.
Since strings are immutable in C#, the Trim() method doesn't change the string itself; it returns a new instance of the trimmed string.
You need to assign the results of the method calls to the variables, i.e.
CFN = Curator_FN.Text.Trim()
And then check whether or not CFN is empty.
Trim does not modify the string. You want:
Curator_FN.Text = Curator_FN.Text.Trim();
CURATOR_ID.Text = CURATOR_ID.Text.Trim();
CURATOR_LN.Text = CURATOR_LN.Text.Trim();
Also, if you're using .NET 4 you might want to check into the String.IsNullOrWhiteSpace method as well.
if (String.IsNullOrWhiteSpace(Curator_FN.Text) ||
String.IsNullOrWhiteSpace(CURATOR_ID.Text) ||
String.IsNullOrWhiteSpace(CURATOR_LN.Text)
{
//..
}
Trim does not modify the string itself. It returns a new trimmed string.
If you don't really care about modifying the variable, look at the IsNullOrWhiteSpace method.
if (String.IsNullOrWhiteSpace(curatorFn) || ... ) {
// show messagebox
}
I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?
I am sure this is a simple question for you guys but I don't know what this developer is doing.
name = String.Format(MyStringBuilder + "");
If I convert this to VB I get the message "operator + is not defined for types system.text.stringbuilder and string". Same thing if I use &.
It looks as if the person who wrote it is attempting to force an implicit conversion of MyStringBuilder to a string using the + operator in conjuction with the empty string.
To perform this assignment in VB you only need:
name = MyStringBuilder.ToString()
In the strictest sense, MyStringBuilder in the original code could be a null instance, at which point making an explicit call to .ToString() would throw an exception. The code sample provided would execute properly, however. In VB, you may want to say
Dim name As String
If MyStringBuilder Is Nothing Then
name = String.Empty
Else
name = MyStringBuilder.ToString()
End If
That doesn't make sense to me because AFAICT passing only one argument to string.format doesn't do anything.
Adding "" to the stringbuilder just coerces it to a string.
name = MyStringBuilder.ToString(); would be how I'd do this in C#. Converting that statement to VB should be loads easier.
Use MyStringBuilder.ToString(). That will fix the problem.
You're trying to concatenate a StringBuilder object and String together - that wouldn't work :)
name = String.Format(MyStringBuilder.ToString() + "");
This should compile correctly.
In VB.NET you would use a "&" instead of a "+"
This line:
name = String.Format(MyStringBuilder + "");
Is causing an implicit cast of MyStringBuilder to string (using the ToString() method) in order to use the "+" operator. It's the same as:
name = String.Format(MyStringBuilder.ToString() + "");
which is the same as
name = MyStringBuilder.ToString();
which becomes this in VB.NET:
name = MyStringBuilder.ToString()