Cannot Solve "index was outside the bounds of the array" - asp.net

I am working in C# with ASP.NET. I am familiar with this error but this time I can't solve it.
I have text in a drop-down list like this:
राम कुमार सिंह 8s2w8r
here राम कुमार सिंह is the name in HINDI while 8s2w8r is users' ID.
I need to separate these two values and need to pass them as session variables. The logic I am using is depicted in the code.
public string reverse(string s)
{
char []temp=s.ToCharArray();
Array.Reverse(temp);
return (temp.ToString());
}
string dropdowntextreversed=reverse(DropDownList1.Text);
char []delim=new char[]{' '};
string []parts=dropdowntextreversed.Split(delim,2);
string family_head_uid = reverse(parts[0]);
string family_head = reverse(parts[1]);
Session.Add("family_head", family_head);
Session.Add("family_head_uid", family_head_uid);
Response.Redirect("/WebForm1.aspx");
I always get an error as the index was outside the bounds of the array! I don't understand this because I am breaking the string into 2 parts so it should have parts[0] and parts[1]. Please suggest...

You are splitting the string into MAXIMUM 2 parts, but if there's only one you will get probably one part.
Read this documentation
Try to assert that parts.Length is == 2 or to access elemnts only there atre two elements

Try this link. As I think there is a problem in the temp.ToString() which will return System.Char[] rather than the value which are you looking for. Use string.join instead will work.

Use the following reverse method:
public string reverse(string s)
{
return String.Join(String.Empty, s.ToCharArray().Reverse());
}

Related

Loadrunner Parameters in JSON String

I'm trying to use a parameter inside of a JSON string, and would like to use an inner parameter to replace an GUID. I've changed the default parameter start and end characters since curly braces are used in JSON.
I've tried to do something like this, where the json param contains my json which is similar to this below.
{"DashboardGUID":"<Dash_GUID>"}
request_json = lr_eval_string("<json>");
lr_save_string(request_json, "request_json_param");
I'm expecting the lr_eval_string to replace the with the GUID that's in this parameter, what's the best why of replacing this ID in my JSON String?
Not sure what you are asking but I will put this here in case someone comes here in the future:
main.c
Action()
{
lr_eval_json("Buffer/File=my_json.json", "JsonObject=MJO",LAST);
lr_json_stringify("JsonObject=MJO","Format=compact", "OutputParam=newJsonBody",LAST);
lr_save_string(lr_eval_string(lr_eval_string("{newJsonBody}")),"tmp");
web_reg_find("Text={mydate}",LAST);
web_rest("POST",
"URL=http://myServer.microfocus.com/url",
"Method=POST",
"EncType=raw",
"Body={tmp}",
HEADERS,
"Name=Content-Type", "Value=application/json", ENDHEADER,
LAST);
return 0;
}
my_json.json
{
"LastActionId": 0,
"Updated": "{mydate}"
}
Okay so instead of doing what I'm thinking above I ended up creating an array of char's with this {"DashboardGUID":"<Dash_GUID>", someotherdata:"123"} in 10 different positions within the array. I then randomly selected an element from this array and when doing the lr_eval_string the parameter was replaced.
Hopefully this makes sense those looking to do something similar.

How to split a string and get all values?

So I've got this small piece of example code in my View
#{
string MyValue = "val1;val2;val3";
}
And I am wondering how I can split it where there's a semi colon, and then I can run through each value and print it in an list
Remember that in a View when using the #{} most C# code can be used. You can use this line with a loop to get what you need done.
string sub = input.Substring(0, input.indexof(";"));

How to remove double qoutes in Objective-C

Let me introduce myself.
My name is Vladimir, C++ programmer, I am from Serbia. two weeks ago I have started to learn objective-C and it was fine until tonight.
Problem:
I cant remove double quotes from my NSLog output.
NSLog(#"The best singers:%#", list.best);
Strings are joined with componentsJoinedByString:#" and "
I would like to get something like this:
The best singers: Mickey and John.
But I get this:
The best singers: ("Mickey", and "John").
I cant remove comma (,) and parentheses either.
I have tried with "replaceOccurencesOfString" but with no success. It can remove any character except qoute and comma.
Also I have used -(NSString *)description method to return string.
You are getting the raw output from your list (which I assume is an array). You will have to do your own formatting to get this to display in the format that you want. You can achieve this by building your string by iterating through your array. Note that this probably isn't the most efficient nor the most robust way to achieve this.
NSMutableString *finalString = [NSMutableString string];
BOOL first = YES;
for (NSString *nameString in list) {
if (first) {
[finalString appendString:nameString];
first = NO;
} else {
[finalString appendString:[NSString stringWithFormat:#" and %#", nameString]];
}
}

Replace string from character onwards

I've got a string like so
Jamie(123)
And I'm trying to just show Jamie without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
One logic; get the index of the ( and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
String.Remove(Int32) will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim() as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()

Adding comma separators to numbers, asp.net

I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function

Resources