-1

i have some combo box but when there is empty i have out of range error.

there is my code :

      string Nom = TBNom.Text;
        string rev = System.Convert.ToString(DropDown.SelectedItem);
        string CONN = System.Convert.ToString(Dconn.SelectedItem);
        string[] speaking = System.Convert.ToString(Dspeaker.SelectedItem).Split(' ');
        string REFHP = speaking[0];
        int powerfull = System.Convert.ToInt32(speaking[1]);
        int impefull = System.Convert.ToInt32(speaking[2]);
        string[] speakingadroite = System.Convert.ToString(DHPD.SelectedItem).Split(' ');
        string refadroite = speakingadroite[0];
        int poweradroite = System.Convert.ToInt32(speakingadroite[1]);
        int impAdroite = System.Convert.ToInt32(speakingadroite[2]);

and on the string [] i have out of range error, i tried with :

    if(speaking[0] != "")

but speaking is not defined anymore.

thanks !

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
  • 2
    if(speaking.Length > 0 && speaking[0] != "") {} – Phong Nguyen Nov 10 '19 at 01:56
  • Can you show us an example string? – tymtam Nov 10 '19 at 02:01
  • Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Stephen Kennedy Nov 10 '19 at 03:34
  • `int powerfull = speaking.Length > 1 ? System.Convert.ToInt32(speaking[1]) : someDefaultValue;` – Rufus L Nov 10 '19 at 05:17
  • Also, instead of `System.Convert.ToString()`, you can just call `.ToString()` on the item, like: `string rev = DropDown.SelectedItem.ToString();` – Rufus L Nov 10 '19 at 05:19

3 Answers3

0

There's a couple things you can do here.

Before splitting on a space, do a check to see if Dspeaker.SelectedItem contains a space:

i.e - string[] speaking = Dspeaker.SelectedItem.ToString().Contains(' ') ? Dspeaker.SelectedItem.ToString().Split(' ') : {};

Second thing you should do is utilize the length property to make sure it was split successfully - i.e - speaking contains at least 1 entry before you try checking it for blank:

if(speaking.Length > 0) {
    Console.WriteLine("Successfully Split!");
}

Split takes a second argument you can pass in, if you're interested in removing blanks: https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

It'd look something like this:

Dspeaker.SelectedItem.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries)

Which would turn:

string test = "me ";

into:

[0] = me

Hope this helps!

dnunez32
  • 224
  • 1
  • 9
0

Out of range Exceptions normally occur when you attempt to access an element in an array that does not exist.

for string[] speaking it looks like your trying to access 3 elements of the array, you should check that the ComboBox being converted to string contains atleast 3 ' ' characters

ex: "This is a string"

that way the results become

speaking[0] = "This";
speaking[1] = "is";
speaking[2] = "a";
speaking[3] = "string";

At this point you can check the size of speaking by using

if (speaking.Length > 0)

if your speaking[] variable does have data and you still can't run the if condition, check that the if condition is being run in the same method of speaking[], or as an alternative you can declare the speaking[] variable in the class and reference it from the method

ex for first method:

...
string[] speaking = System.Convert.ToString(Dconn.SelectItem);
...
if (speaking.Length > 0)
{
...
}

ex for second method:

Class MyClass
{
    string[] speaking = null;
    private void DoMethod()
    {
        speaking = System.Convert.ToString(Dspeaker.SelectedItem).Split(' ');
    }
    private void CheckSpeaking()
    {
        if (speaking != null && speaking.Length > 0)
        {
            // Do Stuff
        }
    }
}

For reference:

https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8 (String.Split documentation)

https://learn.microsoft.com/en-us/dotnet/api/system.array.length?view=netframework-4.8 (array.Length)

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/introduction (Language specification)

Hope that helps

Matthew
  • 1
  • 1
0

Typically you have a couple of choices: Validate the string and throw an exception if it's not in the correct format, or use default values in place of missing items in the string.

The first method would look something like:

string[] speaking = Dspeaker.SelectedItem.ToString().Split(' ');

if (speaking.Length < 3) 
    throw new Exception("The selected item must contain 3 space-separated words);

The second method would look something like:

// Create a default value for integers
var defaultInt = int.MinValue;

string[] speaking = Dspeaker.SelectedItem.ToString().Split(' ');
int length = speaking.Length;

// There will always be a '0' index, so we don't need to check anything first
string REFHP = speaking[0];  

// For the other indexes, check if the index exists before setting a value
int powerfull = length > 1 ? Convert.ToInt32(speaking[1]) : defaultInt;
int impefull = length > 2 ? Convert.ToInt32(speaking[2]) : defaultInt;
Rufus L
  • 36,127
  • 5
  • 30
  • 43