-3

I just started coding with C# and i keep getting this error 'Index was outside the bounds of the array.' and i dont know what i did wrong anyone able to help? I keep getting this message

Index was outside the bounds of the array.

I tried looking around but didnt find anything.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        ChromeDriver driver = new ChromeDriver(@"C:\webdrivers");
        //textbox input
       // string quest = question1.Text;

        //random choise
     
        var random = new Random();
        var Names = question1.Text.Split();
        int index = random.Next();

//the error is here\\
        string randomName = Names[index];
        
        driver.FindElement(By.ClassName("whsOnd")).SendKeys(randomName);
        
        
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        
        ChromeDriver driver = new ChromeDriver(@"C:\webdrivers");
        ChromeDriver drv; Thread th;
        string url = "google.com";

        driver.Navigate().GoToUrl(url);

    }
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 1
    Change `int index = random.Next();` to `int index = random.Next(Names.Length);` – Chronicle Nov 11 '21 at 16:13
  • 2
    `random.Next()` will give you a number between 0 and 2147483647, you don't have that many items in the `Names` array. – DavidG Nov 11 '21 at 16:13
  • Debugger is your friend. Create a breakpoint at `string randomName = Names[index];` and see how many items stored at `var Names` and what is your `index` value. If `index` is greater than amount of `Names` or less than 0 - that's a reason for exception you get. – Auditive Nov 11 '21 at 16:15
  • i have 1 more question i have a list which is connected to a textbox that part works fine but the issue is when i send names i want it to pick the 1st one the the 2nd one and so on... will i need to write the amount of code i need to send each of the names or is there a way around it? sorry if this questions are stupid but really confused. Sorry. – golden leo Nov 11 '21 at 16:56

1 Answers1

-1

"Index was outside the bounds of the array" suggests that the random index generated is larger than the size of your Names array

DTynewydd
  • 310
  • 4
  • 10
  • This is more of a comment than an answer. In fact, some of the comments are better answers (and, no, I'm not the downvoter). – Flydog57 Nov 11 '21 at 17:07
  • But it does answer the question of "What's going wrong with my code?". It doesn't provide a solution but it does help the OP to find the solution. – DTynewydd Nov 12 '21 at 08:32