Value '0' não é um valor válido para 'SelectedIndex'.

System.ArgumentOutOfRangeException was unhandled
  HResult=-2146233086
  Message=InvalidArgument=Value '0' não é um valor válido para 'SelectedIndex'.
Nome do parâmetro: SelectedIndex
  Source=System.Windows.Forms
  ParamName=SelectedIndex
  StackTrace:
       em System.Windows.Forms.ComboBox.set_SelectedIndex(Int32 value)
       em RemoteConsole.MainForm.AddMailTypeList(List`1 typeList) na D:\zhyz\Server Source\RemoteConsole\RemoteConsole\MainForm.cs:linha 124
       em RemoteConsole.Program.Main() na D:\zhyz\Server Source\RemoteConsole\RemoteConsole\Program.cs:linha 74
       em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       em System.Threading.ThreadHelper.ThreadStart()
  InnerException:


Code:        public void AddMailTypeList(List<MailTypeCfg> typeList)
        {
            foreach (MailTypeCfg ty in typeList)
            {
                comboBox2.Items.Add(ty.desc);
            }
            comboBox2.BeginUpdate();
            comboBox2.SelectedIndex = 0;
            comboBox2.EndUpdate();
        }

Help Pls!
Lucas LópezAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
It sounds like the list typeList is empty no items in it. Place a breakpoint on the first line in the function and check to make sure it does in fact have items an that it is not empty.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Miguel OzSoftware EngineerCommented:
See code below, first part deal with empty list and the second part loads the combo box within being/end update context:
public void AddMailTypeList(List<MailTypeCfg> typeList)
{
    if(typeList.Count == 0)
	{
		//Empty comboBox2 as there is no value to fill up, unless it is been done else where.
		comboBox2.Items.Clear();
		return;  
	}

    comboBox2.BeginUpdate();
	//All UI code must be inside begin/end update
	try
	{
		foreach (MailTypeCfg ty in typeList)
		{
			comboBox2.Items.Add(ty.desc);
		}
		comboBox2.SelectedIndex = 0;
	}
	finally
	{
		comboBox2.EndUpdate();
	}
}

Open in new window

0
it_saigeDeveloperCommented:
Since you are dealing with a list of objects, rather than adding items to your ComboBox, why not take advantage of the Datasource property; e.g. -

Form1.cs -
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace EE_Q29075213
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void AddMailTypeList(List<MailTypeConfig> typeList)
        {
            comboBox1.BeginUpdate();
            comboBox1.DataSource = (from item in typeList
                                    select new
                                    {
                                        DisplayMember = item.desc,
                                        ValueMember = item
                                    }).ToList();
            comboBox1.DisplayMember = "DisplayMember";
            comboBox1.ValueMember = "ValueMember";
            if (comboBox1.Items.Count > 0)
                comboBox1.SelectedIndex = 0;
            comboBox1.EndUpdate();
        }

        void OnSelectedValueChanged(object sender, EventArgs e)
        {
            if (sender is ComboBox)
            {
                var cb = sender as ComboBox;
                textBox1.AppendText(string.Format("Selected - {0}; Value = {1}\r\n", cb.Text, cb.SelectedValue as MailTypeConfig));
            }
        }

        void OnLoad(object sender, EventArgs e)
        {
            AddMailTypeList((from i in Enumerable.Range(0, 20) select new MailTypeConfig { desc = string.Format("Desc{0}", i), name = string.Format("Name{0}", i), birthDate = DateTime.Now.AddDays(-(i * 9)) }).ToList());
        }
    }

    class MailTypeConfig
    {
        public string desc { get; set; }
        public string name { get; set; }
        public DateTime birthDate { get; set; }

        public override string ToString()
        {
            return string.Format("Name: {0}; BirthDate: {1}", name, birthDate.ToString("MM/dd/yyyy"));
        }
    }
}

Open in new window

Form1.Designer.cs =
namespace EE_Q29075213
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(105, 13);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(167, 21);
            this.comboBox1.TabIndex = 0;
            this.comboBox1.SelectedValueChanged += new System.EventHandler(this.OnSelectedValueChanged);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(87, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Select an option:";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(15, 41);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.Size = new System.Drawing.Size(256, 208);
            this.textBox1.TabIndex = 2;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.comboBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.OnLoad);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
    }
}

Open in new window

Produces the following output -
Initial load -Capture.PNGDrop down contains -Capture.PNGIf we select another item -Capture.PNG
-saige-
0
Fernando SotoRetiredCommented:
All solutions show ways to handle the problem.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.