Pergunta

"IndexOutOfRangeException was unhandled"

string ebtocosname;
ebtocosname = webBrowser2.Document.GetElementById("Fullname").GetAttribute("value");
var NAMES = ebtocosname.Split();

 webBrowser1.Document.GetElementById("FirstName").SetAttribute("value", NAMES[0]);

 webBrowser1.Document.GetElementById("LastName").SetAttribute("value", NAMES[1]);     // This line here shows that IndexOutofRangeException was unhandled

The value of "Fullname" has only one name on it. So it should only write NAMES[0] in the "FirstName" and leave blank on the "LastName."

BUT BUT BUT but it stopped and it showed that the very last line of the code was "IndexOutOfRangeException was unhandled"

And also, it only works well if the value of "Fullname" has two names on it.

How can I make it work in such a way that it wouldn't stop even if there's no NAMES[1] in the value of "Fullname?"

What I'm trying to do is transferring the value of "Fullname" by splitting it to the "FirstName" and the "LastName." But sometimes the value of the "Fullname" doesn't contain a last name... And then my program stops and says "IndexOutOfRangeException was unhandled"

Please help me! how can I make this work, I wrote a lot of IF Statements to deal with this kind of situation when variable NAMES[1] doesn't exist in the "Fullname", and yet it still shows ""IndexOutOfRangeException was unhandled"

Foi útil?

Solução

Just check if your split yielded ore or two values:

if(NAMES.Length == 2)
   webBrowser1.Document.GetElementById("LastName").SetAttribute("value", NAMES[1]);     

Of course, this assumes that you have no other problems like:

  • the user did not enter any input
  • the user entered more than two names
  • the user entered some unacceptable characters

etc.

You should plan your input verification more carefully to catch any other strange behavior.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top