Search code examples
c#comboboxvideo-captureaforgeselectedindex

System.ArgumentOutOfRangeException: InvalidArgument=Value of '0' is not valid for 'SelectedIndex'


If this way I can list exist video capture devices:

    foreach (FilterInfo Device in CaptureDevice)
    {
        comboBox1.Items.Add(Device.Name);
    }

How to avoid exception in case if device just does not exist on machine:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '0' is not valid for 'SelectedIndex'. Parameter name: SelectedIndex at System.Windows.Forms.ComboBox.set_SelectedIndex(Int32 value)


Solution

  • before you add Device.Name, check if it exists in the first place

    if(Device!= null){
         comboBox1.Items.Add(Device.Name);
    }
    

    Also, create a boolean that indicates a device does not exist, and if it is found switch it to true. Something like bool devExist = false; and when device is not null, devExist = true. Then you'd know if no device is there and you wouldn't try to access it if iti's not there if(devExist) { //do something }