我有一个listView,当我从listview中选择其他值时,它会给出错误
invalid argument value of 0 is not valid for index
代码是这样的:
UserList = getUsers();
for (int i = 0; i < UserList.Count; i++)
{
User user = UserList.ElementAt(i);
ListViewItem row = new ListViewItem();
row.Text = user.name.ToString();
row.SubItems.Add(user.surname);
row.Tag = user.weight.ToString();
row.Tag = user.height.ToString();
row.Tag = user.id;
listView1.Items.Add(row);
}
userList是来自xml文件的列表:
public List<User> getUsers()
{
XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/users/user");
foreach (XmlNode node in nodes)
{
User user = new User();
user.id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
user.name = node.SelectSingleNode("name").InnerText;
user.surname = node.SelectSingleNode("surname").InnerText;
user.weight = Convert.ToInt32(node.SelectSingleNode("weight").InnerText);
user.height = Convert.ToInt32(node.SelectSingleNode("height").InnerText);
UserList.Add(user);
}
return UserList;
}
如何摆脱错误?
- 编辑:
它在这里出错:
public List<UserData> getAllUsers()
{
var id = (int)listView1.SelectedItems[0].Tag; // ERROR in this line
var currenTask = UserList.Where(t => t.id == id).First();
SqlConnection conn = Program.getConnection;
SqlDataReader rdr = null;
try
{
string query = "SELECT * FROM personalData where user_id = @user_id";
SqlCommand cmd = new SqlCommand(query, conn);
SqlParameter user_id = cmd.Parameters.Add("@user_id", SqlDbType.Int);
user_id.Value = currenTask.id;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
UserData userData = new UserData();
userData.id = rdr.GetInt32(0);
userData.mode = rdr.GetString(1);
userData.time_preview = rdr.GetString(2);
userData.time = rdr.GetInt32(3);
userData.callories_lost = rdr.GetDouble(4);
userData.date = rdr.GetDateTime(5);
userData.user_id = rdr.GetInt32(6);
userData = userData.createUser(userData.id, userData.mode, userData.time_preview, userData.time, userData.callories_lost, userData.date, userData.user_id);
UserDataList.Add(userData);
}
rdr.Close();
}
finally
{
if (rdr != null) { rdr.Close(); }
if (conn != null) { conn.Close(); }
}
return UserDataList;
}
错误在评论中
答案 0 :(得分:0)
如果没有用户怎么办?您的循环仍将运行,因为0不小于0.
使用<=
代替<
。
for (int i = 0; i <= UserList.Count; i++)