Reputation: 81
I have build a program that converts DBF files and shows them in a Datagridview (C#).
It has a column in there that contains the initials & the appointment itself.
I also have made a program already that splits the initials and inserts them into the database.
Without going further into the program itself I would like to ask, how to I split the string?
Example of data in a Cell; "WKO/JVM/RZO: Ingmar Boelens (GT)"
So every cell has data in it which contains the initials, followed by a ":" and then the appointment itself.
The code that I am using right now;
string appointment;
if (!string.IsNullOrWhiteSpace(row.Cells[2].Value.ToString()))
{
appointment = row.Cells[2].Value.ToString();
}
else
{
appointment = "No data available";
}
if (!string.IsNullOrWhiteSpace(appointment ))
{
appointment += " ";
appointment = appointment.Substring(appointment.IndexOf(':') + 1, appointment.LastIndexOf(' '));
}
else
{
appointment = "No data available";
}
So basically what I try is adding a white space at the end of every string, so that I can split them from the ":" to the last white space.
However it doesn't work and I get an error saying "ArgumentOutOfRangeException". But not anything specific.
I know that where I try to split the second part of the string is not a legitimate condition, but how can I solve this?
Upvotes: 1
Views: 160
Reputation: 3653
The second argument of string.Substring()
is Length, so the length FROM appointment.IndexOf(':') + 1 is being returned. You're getting the exception because the interval you are adding to the first argument exceeds the actual length of the string. What you should do is subtract the first indexOf from the second, so:
appointment = appointment.Substring(appointment.IndexOf(':') + 1, appointment.LastIndexOf(' ') - appointment.IndexOf(':'));
So basically what I try is adding a white space at the end of every string, so that I can split them from the ":" to the last white space.
Oh. You don't have to do that. You can just do:
appointment = appointment.Substring(appointment.IndexOf(':')+1, appointment.Length - appointment.IndexOf(':')-1).Trim()
Upvotes: 1
Reputation: 4954
string s = "WKO/JVM/RZO: Ingmar Boelens (GT)";
string[] words = s.Split(':');
/*
* words[0]= "WKO/JVM/RZO"
* words[1] = "Ingmar Boelens (GT)";
*
*/
string[] data= = words[0].Split("/");
/*
* data[0]= "WKO";
* data[1] = "JVM";
* data[2] = "RZO";
*/
Upvotes: 1