ArgumentOutOfRangeException and updateControls method
I am just a student begining to study C#, so I apologize if my questions are not very clear. I am stuck for the answer. I don't know how to code the ArgumentOutofRangeException, so the user doesn't go beyond the edges of the Lists. I have 2 of them, with two index variables. I also have a problem with updateControls. Any help would be greatly appreciated.
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();
}
if (cboType.SelectedItem.ToString() == "Residential"
&& currentResIndex < resList.Count -1) // add this condition
currentResIndex++;
updateControls();
You could just enforce the range in your btnNext_Click
method:
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();
}
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
}
But imho you shouldn't be using this. You should check whether or not the end of the List is reached.
精彩评论