Click here to Skip to main content
15,846,342 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i bind the list box
i am getting error there is no row at position 6

if deleting 6 then there is no row at position 5

public void bindlistbox()
{
DataSet ds = new DataSet();
string query = "select FName from UserInformation";
SqlDataAdapter da = new SqlDataAdapter(query, c);
//da.SelectCommand.CommandType = CommandType.StoredProcedure;
// da.SelectCommand.Parameters.AddWithValue("@UserId", UserId);
//da.SelectCommand.Parameters.AddWithValue("@FName", fname);
da.Fill(ds);
for (int i = 0; i <= ds.Tables[0].Rows.Count; i++)
{

lstuser.Items.Add(ds.Tables[0].Rows[i]["FName"].ToString());

}
Posted

1 solution

Change your for line to be:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

If your count is 6, you need to iterate 0 to 5 ie (0, 1, 2, 3, 4, 5)
 
Share this answer
 
Comments
Member 9425683 19-Feb-14 1:42am    
this is right but if i am using this from 1 to 6 again error can you explain me
NeverJustHere 19-Feb-14 3:53am    
The Row index is 0-based, not 1-based. This is why the for loop starts with i=0. When Rows.Count = 6, the 6 valid Rows[i] are where i = 0,1,2,3,4,5.

(Other languages would use 1-based arrays, but c# is 0-based)

If you try to access Rows[6], you are asking for the 7th Row, which doesn't exist - hence the error.

An alternate way of iterating through the Rows collection is to use the for each loop

Foreach (DataRow row in ds.Tables[0].Rows)
{
lstuser.Items.Add(row["FName"].ToString());
}

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