developthestars
developthestars

Reputation: 185

Multiple lengths for substring?

Can a substring have mutiple arguments? I am pulling a substring from a drop down list into my database for records, the string is between 6 and 8 numbers, is it possible to pass more than one argument to make this work?

Sample data:

DropDownList

123456 | Name 
1234567 | Name 
12345678 | Name 

dt = ExecuteStoredProcedure(SqlConnection, "InsertData", "@name", ddlE_VN.SelectedValue.Substring(0, 6))

Upvotes: 2

Views: 242

Answers (2)

KennyZ
KennyZ

Reputation: 907

Based on the data you show, this should work :

ddlE_VN.SelectedValue.Substring(0, ddlE_VN.SelectedValue.IndexOf(' '))

We are starting our substring at index 0, which is the first character. If the space is the sixth character, it will have an index of 5, so we will return the first 5 characters. If the space is the eighth character, it will have an index of 7, so we will return the first 7 characters, etc.

Upvotes: 3

Wouter de Kort
Wouter de Kort

Reputation: 39898

Substring can take only a start parameter and return the substring till the end of the string.

If your substring is separated with spaces or some other character, you could calculate the index of the delimiter and use that in your substring.

Something like this:

string myString = "part1 part2 part3";

int firstSpace = myString.IndexOf(' ');
int secondSpace = myString.LastIndexOf(' ');

string part1 = myString.Substring(0, firstSpace).Trim();
string part2 = myString.Substring(firstSpace, secondSpace - firstSpace).Trim();
string part3 = myString.Substring(secondSpace).Trim();

Off course, you can also use regular expressions for this but since your sample data is not that complicated I personally prefer this code.

Upvotes: 0

Related Questions