我只是一名学生开始学习C#,所以如果我的问题不是很清楚,我会道歉。我被困在了答案中。我不知道如何编写ArgumentOutofRangeException代码,因此用户不会超出列表的边缘。我有两个,有两个索引变量。我也有updateControls的问题。任何帮助将不胜感激。
private void updateControls()
{
pictureBox1.Image = resList[currentResIndex].Photo;
lblName.Text = resList[currentResIndex].Title;
lblCity.Text = resList[currentResIndex].City;
lblPrice.Text = resList[currentResIndex].Price.ToString("C");
pictureBox1.Image = comList[currentCommIndex].Photo;
lblName.Text = comList[currentCommIndex].Title;
lblCity.Text = comList[currentCommIndex].City;
lblPrice.Text = comList[currentCommIndex].Price.ToString("C");
}
private void btnNext_Click(object sender, EventArgs e)
{
if (cboType.SelectedItem.ToString() == "Residential") //if they chose residential then increment resIndex
currentResIndex++;
updateControls();
else
currentCommIndex++;//or else commIndex
updateControls();
}
答案 0 :(得分:0)
您可以在btnNext_Click
方法中强制执行范围:
private void btnNext_Click(object sender, EventArgs e)
{
if (cboType.SelectedItem.ToString() == "Residential")//if they chose residential then increment resIndex
currentResIndex++;
else
currentCommIndex++;//or else commIndex
currentCommIndex = Math.Min(comList.Length-1, currentCommIndex);
currentResIndex = Math.Min(resList.Length-1, currentResIndex);
updateControls();
}
答案 1 :(得分:0)
if (cboType.SelectedItem.ToString() == "Residential"
&& currentResIndex < resList.Count -1) // add this condition
currentResIndex++;
updateControls();
答案 2 :(得分:0)
try
{
if (cboType.SelectedItem.ToString() == "Residential") //if they chose residential then increment resIndex
{
currentResIndex++;
}
else
{
currentCommIndex++;//or else commIndex
}
updateControls();
}
catch (ArgumentOutOfRangeException ex)
{
//Do the things you want when this exception occurs
}
但你不应该使用这个。您应该检查是否到达列表的末尾。