Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
cm.Command.Parameters.Add("@FeedID", SqlDbType.SmallInt).Value = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
Posted

This Exception is thrown when you try to access an item in a collection by its index, but the index does not exist.
For example, you have the following collection:
c = {"Zero", "One", "Two", "Three"}

Now imagine you want "Zero", you'd say c[0], which is fine.
Now say you want "Four", you'd say c[4], but there is no "Four"! At this time the Exception would be thrown.

In this case your grid either has less rows than GridView1.SelectedIndex or it has no Cells.
It probably has Cells, so I suspect GridView1.SelectedIndex is not returning what you expect :)

For more information on the IndexOutOfRangeException see the MSDN page for IndexOutOfRangeException[^].
 
Share this answer
 
v2
if there is no selection SelectedIndex will have -1, add validation for that case
C#
if(GridView1.SelectedIndex>=0)
{
  cm.Command.Parameters.Add("@FeedID", SqlDbType.SmallInt).Value = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
}
 
Share this answer
 
v2
Check your event handler: you will get an event when no item is selected (particularly when you load the control) and the SelectedIndex will be -1 in that case to indicate it.

You should add a test to check before you try and use the index!
 
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