remove last two string char! - asp.net

The following code:
If checkboxList.Items(i).Selected Then
.Fields("DESC1").Value += checkboxList.Items(i).Text + ", "
End If
should produce output such as "A, B, C,(space)", which will then be bound to a dynamically created GridView. I would like to remove the last two-char string, that is ",(space)". How can I do this?

Take a look at String.Join, which may do what you want, without the need to manipulate the final two characters.

I wouldn't add them on in the first place :) try
If checkboxList.Items(i).Selected Then
if .Fields("DESC1").Value Is System.DbNull.Value then
.Fields("DESC1").Value = checkboxList.Items(i).Text
else
.Fields("DESC1").Value += ", " + checkboxList.Items(i).Text
End If
End If

For info, string concatenation is expensive. It looks (from the i and from the results) like you should really be using a StringBuilder; some rough pseudo-code (in C#, but trivial to translate to VB.Net):
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < checkboxList.Items.Count ; i++) {
if(checkboxList.Items[i].Selected) {
if(sb.Length > 0) sb.Append(", "); // add separator
sb.Append(checkboxList.Items[i].Text); // add text
}
}
someOjb.Fields("DESC1") = sb.ToString(); // use result

You can use .TrimEnd(", ".ToCharArray()) on the string, or you can use SubString:
strLetters.Substring(0, strLetters.Length - 2)

It seems you just want to get "A, B, C" from "A, B, C, ". A bit of simple string manipulation should do the job:
Dim input = "A, B, C, "
Dim result = input.Substring(0, input.LastIndexOf(","))
This is more versatile than simply removing the last two characters, since it looks for the last comma, which is what I believe you are after.
Of course, the fact that you're adding on these two chars in the first place sounds a bit dodgy. I'd need to see more context to show how this can be avoided, however.

use
.Fields("DESC1").Value += checkboxList.Items(i).Text + ", "
. Fields("DESC1").Value = .Fields("DESC1").Value.TrimRight(new []{',',' '});
PS:- sorry if it is not valid vb syntax :)

There is also just "Remove":
string k = "okay";
string s = k.Remove(k.Length - 2, 2);

This will remove all trailing , and/or [space]:
.Fields("DESC1").Value = .Fields("DESC1").Value.TrimRight(", ".ToCharArrray())

var selectedValues = checkboxList.Items
.Where(i => i.Selected)
.Select(i => i.Fields("DESC1").Value);
var result = String.Join(", ", selectedValues);

Does VB have a ternary if operator?
If checkboxList.Items(i).Selected Then
.Fields("DESC1").Value += checkboxList.Items(i).Text + (i == checkboxList.Items.Length-1 ? "" : ", ")
End If

Related

How to get the last two sections of a URL

When the URL is: http://www.example.com/services/product/Software.aspx , I need: "product/Software.aspx",
So far I just tried the below code :
string[] SplitUrls = Request.RawURL.Split('/');
string CategorynQuery = SplitUrls[SplitUrls.Length - 2]
+ SplitUrls[SplitUrls.Length - 1];
However, is there some other way to do this using functions IndexOf(), LastIndexOf() etc.. or any other Function? Or any possibility using Substring method ?
Please note that the above URL is just an example, there are around 100 such URls and I need the Last 2 sections for each.
Try this, using the LastIndexOf, and Substring.
string str = "http://www.example.com/services/product/Software.aspx";
int lastIndexOfBackSlash = str.LastIndexOf('/');
int secondLastIndex = lastIndexOfBackSlash > 0 ? str.LastIndexOf('/', lastIndexOfBackSlash - 1) : -1;
string result = str.Substring(secondLastIndex, str.Length - secondLastIndex);
I am also checking the presence when getting the second last index - obviously you can alter this depending on your requirements :)
You can use Uri class:
Uri uri = new Uri("http://myUrl/%2E%2E/%2E%2E");
uri.AbsoluteUri;
uri.PathAndQuery;
Not too efficient but a little more elegant:
string url = "http://www.example.com/services/product/Software.aspx";
var splitted = url.Split('/').Reverse().Take(2).Reverse().ToList();
var str = string.Format("{0}/{1}", splitted[0], splitted[1]);

How to check if the string contains only slash symbol in it?

How to check if the string contains only / symbol in it ? The string may have more than one / symbols with white spaces in between. In such cases i want to consider that the string is empty.
In c# the answer would be:
if (yourText.Count(x => (x != '/') && (x != ' ')) > 0)
{
//not empty
}
Basicly: "if the count of all the characters which are not "/" or a space is greater than 0"
I have not done VB in a while, but translating it should not be hard. You could just do for-loop approach
Dim isEmpty as Boolean = true;
For (Dim i as Integer = 0 to yourText.Length - 1)
If (yourText[i] <> "/"C And yourText[i] <> " "C) Then
isEmpty = false;
End If
Next
Again, I am doing this completely from memory, so excuse me if my syntax is off. Correct my code if I have an error.

Trim function not removing spaces in name

bool Res = false;
DataView DV = new DataView(DT);
DV.RowFilter = "Trim(Originator)='"+OrginatorName.Trim()+"'";
if (DV.Count > 0)
{
Res = true;
}
I need to get "Originator" from the database and compare it with the OrginatorName to check duplicate values. I need to remove all the white spaces before checking.
For example, the function must consider "John Van" to be the same as "JohnVan". My above code doesn't work. How can I achieve this?
String.Trim() removes whitespace from the beginning and end only, not in the middle. You want to use the String.Replace() method
DV.RowFilter = "Trim(Originator)='"+OrginatorName.Replace(" ", "")+"'";
this line should be
DV.RowFilter = "Trim(Originator)='"+OrginatorName.Replace(" ","")+"'";
User .Replace instead of .Trim()

C# alternative for javascript escape function

what is an alternative for javascript escape function in c# for e.g suppose a string:"Hi Foster's i'm missing /you" will give "Hi%20Foster%27s%20i%27m%20missing%20/you" if we use javascript escape function, but what is the alternative for c#. i have searched for it but no use.
You can use:
string encoded = HttpUtility.JavaScriptStringEncode(str);
Note: You need at least ASP.NET 4.0 to run the above code.
var unescapedString = Microsoft.JScript.GlobalObject.unescape(yourEscapedString);
var escapedString = Microsoft.JScript.GlobalObject.escape(yourUnescapedString);
The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.
Following is the escape function implementation that you will find in Microsoft.JScript.dll...
[NotRecommended("escape"), JSFunction(JSFunctionAttributeEnum.None, JSBuiltin.Global_escape)]
public static string escape(string str)
{
string str2 = "0123456789ABCDEF";
int length = str.Length;
StringBuilder builder = new StringBuilder(length * 2);
int num3 = -1;
while (++num3 < length)
{
char ch = str[num3];
int num2 = ch;
if ((((0x41 > num2) || (num2 > 90)) &&
((0x61 > num2) || (num2 > 0x7a))) &&
((0x30 > num2) || (num2 > 0x39)))
{
switch (ch)
{
case '#':
case '*':
case '_':
case '+':
case '-':
case '.':
case '/':
goto Label_0125;
}
builder.Append('%');
if (num2 < 0x100)
{
builder.Append(str2[num2 / 0x10]);
ch = str2[num2 % 0x10];
}
else
{
builder.Append('u');
builder.Append(str2[(num2 >> 12) % 0x10]);
builder.Append(str2[(num2 >> 8) % 0x10]);
builder.Append(str2[(num2 >> 4) % 0x10]);
ch = str2[num2 % 0x10];
}
}
Label_0125:
builder.Append(ch);
}
return builder.ToString();
}
Code taken from Reflector.
The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.
I noticed another solution in the comments in KodeSharp article that may be better. The comment says it is more compatible with UTF-8 and does not require the reference to JScript. Is this better?
(Dependent on System.Web.Extensions.dll)
using System.Web.Script.Serialization;
JavaScriptSerializer serialiser = new JavaScriptSerializer();
serialiser.Serialize("some \"string\"")
string myString = "Hello my friend";
myString = myString.Replace(" ", "%20");
This would replace all " " with "%20".
Is this what you wanted?
You can try this
Uri.EscapeDataString(Obj);

Function to convert "camel case" type text to text with spaces in between? ie: HelloWorld --> Hello World

Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World
It would be nice to be able to handle all these situations.
Preferably in in VB.Net, or C#.
I donĀ“t know if this is the most efficient way. But this method works fine:
EDIT 1: I have include Char.IsUpper suggestion in the comments
EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)
EDIT 3: I've used StringBuilder, like #Dan commented.
public string CamelCaseToTextWithSpaces(string input)
{
StringBuilder output = new StringBuilder();
input = input.Replace("_", "");
foreach (char character in input)
{
if (char.IsUpper(character))
{
output.Append(' ');
}
if (output.Length == 0)
{
// The first letter must be always UpperCase
output.Append(Char.ToUpper(character));
}
else
{
output.Append(character);
}
}
return output.ToString().Trim();
}
There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.
I'd recommend using:
Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)
Public Function CamelCaseToWords(CamelCaseString As String) As String
Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function
'Gives:
'CamelCase => Camel Case
'PIN => PIN
What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.
Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.
private static string BreakUpCamelCase(string s)
{
MatchCollection MC = Regex.Matches(s, #"[0-9a-z][A-Z]");
int LastMatch = 0;
System.Text.StringBuilder SB = new StringBuilder();
foreach (Match M in MC)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
LastMatch = M.Index + 1;
}
if (LastMatch < s.Length)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch));
}
return SB.ToString();
}

Resources