Click here to Skip to main content
15,883,901 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is the error>
************** Exception Text **************
System.ArgumentOutOfRangeException: InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.
Parameter name: SelectedIndex

my code>

C#
DataSet st = new DataSet();
           string strConnectionString = "Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True";

           SqlConnection objconnection = new SqlConnection(strConnectionString);
           using (SqlCommand cmd = new SqlCommand("SELECT  [name] FROM [staff1]",
           objconnection))
           {
               using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
               {
                   adapter.Fill(st);
               }
           }

           var empList = st.Tables[0].AsEnumerable().Select(dataRow =>

           dataRow.Field<string>("name")).ToList();

           listBox1.SelectedIndex = 0;
           listBox1.Update();

I dont understand the issue.It worked 10 mins ago but now it doesn't? I am really confused any help would be apreciated
Posted
Updated 31-Aug-15 2:37am
v2
Comments
phil.o 31-Aug-15 8:22am    
How many items does your listbox contain when you get the exception? If it is empty, there is no item at index 0, thus the exception.
jamesmc1535 31-Aug-15 8:23am    
0 at the moment but i have an add option , when i add to the database it still does the same
jamesmc1535 31-Aug-15 8:25am    
never mind fixed it , > listBox1.DataSource = empList;> was accidently removed
Pikoh 31-Aug-15 8:26am    
Well..in the code you just send, you never fill the listbox with data, something like:

listBox1.DataSource = emplist;
this.listBox1.DisplayMember = ... ;
this.listBox1.ValueMember = ... ;

1 solution

It means that you are trying to select an item in a list with 0 item count. If you had at least one item, the index 0 would be valid. Just 1) use the debugger; 2) don't address anything by index without checking the count, which would give your the valid range of indices 0 to count − 1, which you should check up.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900