4

I have created a Windows Form App which is connected to a database and users enter specific values in it. The problem I'm facing right now is that I created a search, which works like charm. But, users will always search by Name and Surname, and I wanted to trim this search to be more accuarate. It works, but when I enter only Name or only Surname, I'd like to show a massageBox to say that they didn't enter properly. So I wrote this, but if I type only one word, it crashes and shows this error: Index was outside the bounds of array. Thanks !

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text.Length != 0)
    {
        var numePrenume = textBox1.Text.Trim().Split(' ');
        var nume = numePrenume[0];
        var prenume = numePrenume[1];

    if (nume.Length > 0 || prenume.Length > 0)
    {
        var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
        using (var conn = new SqlCeConnection(connString))
        {
        }
    }

    //some code
}
vidriduch
  • 4,753
  • 8
  • 41
  • 63
Ezekiel
  • 333
  • 4
  • 9
  • 27
  • What is the `textBox1.Text` exactly? Have you ever debug your code and see? If it has one word, this `Split` doesn't return as a second value of course. That's why there will be no `numePrenume[1]` items. Also read: http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it – Soner Gönül Aug 21 '15 at 08:12
  • Sure. textBox1.Text is the text entered for search in the text with that id assigned – Ezekiel Aug 21 '15 at 08:14
  • But it's clear that your split return only one string, so your numePrenume will have only a 0 index value – MRebai Aug 21 '15 at 08:15
  • I know that.. I understand why is crashing and why is showing the error. But I don't really know how to solve it . – Ezekiel Aug 21 '15 at 08:17

7 Answers7

2

Check your array length will fix your issue :

 if (textBox1.Text.Length != 0)
            {

                var numePrenume = textBox1.Text.Trim().Split(' ');
                if (numePrenume.Length >= 1)
                {
                    var nume = numePrenume[0];
                    var prenume = numePrenume[1];

                    if (nume.Length > 0 || prenume.Length > 0)
                    {
                        var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
                        using (var conn = new SqlCeConnection(connString))
                        {
                        }
                    }
                }
                else
                    // some code here
            }
MRebai
  • 5,344
  • 3
  • 33
  • 52
2

You'll need to check the length of the array returned by Split(). In addition it is a good idea to add StringSplitOptions.RemoveEmptyEntries to avoid getting more than two parts if the user types multiple spaces between the name parts.

Consider this example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var name = "   name  ";

            var nameParts = name.Trim().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);

            if (nameParts.Length < 2)
            {
                Console.WriteLine("You've only entered one name");
            }
            else
            {
                Console.WriteLine("First part: {0}", nameParts[0]);
                Console.WriteLine("Second part: {0}", nameParts[1]);
            }
        }
    }
}
Micke
  • 2,251
  • 5
  • 33
  • 48
  • The key here is the `Length` check of `nameParts`, or `numePrenume` in your code: `if (numePrenume.Length < 2) { // Do something! } else { // Connect to the DB ... }` – Micke Aug 21 '15 at 08:31
  • Got that. But really can't understand why's not working. – Ezekiel Aug 21 '15 at 08:31
  • If the user enters a single name, numePrenume will only contain one single item. `numePrenume[1]` will try to fetch item #2, which is out of bounds of the array. – Micke Aug 21 '15 at 08:33
1

If you type only one word, then this line will cause the exception:

var prenume = numePrenume[1];

Because it does not exist.

You need to add some bounds checking before trying to access that element of the array, e.g.

if(numePrenume.Length == 2)
{
    var prenume = numePrenume[1];
}
Stuart Grassie
  • 3,043
  • 1
  • 27
  • 36
1

You need to check if the split function returns more then one element. Simple updating your code like this should solve your problem:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text.Length != 0)
    {
        var numePrenume = textBox1.Text.Trim().Split(' ');
        var nume = numePrenume[0];

        if(numePrenume.Length >= 1) 
        {
            var prenume = numePrenume[1];
        }

        if (nume.Length > 0 || prenume.Length > 0)
        {
            var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
            using (var conn = new SqlCeConnection(connString))
            {
            }
        }
        //some code
    }
Maurits van Beusekom
  • 5,579
  • 3
  • 21
  • 35
1

You need to check if numePrenume.Length is more than 1. If it less than 1, show up some message to user.

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text.Length != 0)
    {
        var numePrenume = textBox1.Text.Trim().Split(' ');
        if(numePrenume.Length > 1)
        {
            var nume = numePrenume[0];
            var prenume = numePrenume[1];

            if (nume.Length > 0 || prenume.Length > 0)
            {
                var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
                using (var conn = new SqlCeConnection(connString))
                {
                }
            }
                    //some code
         }
         else
         {
              Console.Writeline("You need to input both Name and Surname");
         }
    }
}
currarpickt
  • 2,290
  • 4
  • 24
  • 39
1

You need to check whether the Split(' ') got you 2 names. It can't give you a numePrenume[1] if it only contains one element.

Untested Code:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text.Length != 0)
    {
        var numePrenume = textBox1.Text.Trim().Split(' ');

        if(numePrenume.Count()>1)
        {
            var nume = numePrenume[0];
            var prenume = numePrenume[1];

            var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
            using (var conn = new SqlCeConnection(connString))
            {
            }
        }

        //some code
    }

}
Boti
  • 11
  • 2
0

you can try by validating the Textbox.Text and if you require to be populated both Name and surname, you can return validation Error. this can be done as follows:

if(numePrenume.Lenght()==0)
{
   MessageBox.Show("");
}

 return;

hope it helps :)

Petar Minev
  • 498
  • 1
  • 5
  • 10