我正在尝试在循环中执行ifs。编译器说“发生了未处理的异常”。有任何想法吗?评论的代码正在运行。中的一个不是。 for应该是更优化的。 编辑:对不起忘了说所有的ComboBox和TetBox都在数组中。
ComboBox[] ComboBoxes = new ComboBox[3];
ComboBoxes[0] = comboBox1;
ComboBoxes[1] = comboBox2;
ComboBoxes[2] = comboBox3;
工作代码:
if (comboBox1.Text == "Cheese" || comboBox1.Text == "Vegetable" || comboBox1.Text == "Meat")
{
if (comboBox2.Text == "Cheese" || comboBox2.Text == "Vegetable" || comboBox2.Text == "Meat")
{
if (comboBox3.Text == "Cheese" || comboBox3.Text == "Vegetable" || comboBox3.Text == "Meat")
{
return true;
}
else { comboBox3.Text = "Wrong input"; return false; }
}
else { comboBox2.Text = "Wrong input"; return false; }
}
else { comboBox1.Text = "Wrong input"; return false; }
最佳无效版本:
int isvalid = 0;
for (int i = 0; i < 3; i++)
{
if (ComboBoxes[i].Text == "Cheese" || ComboBoxes[i].Text == "Vegetable" || ComboBoxes[i].Text == "Meat")
{
isvalid++;
}
else { ComboBoxes[i].Text = "Wrong input"; }
}
if (isvalid == 3)
{
return true;
}
else { return false; }
答案 0 :(得分:0)
int isvalid = 0;
List<string> foods = new List<string> { "Cheese", "Vegetable", "Meat" };
List<string> cbNames = new List<string> { "comboBox1", "comboBox2", "comboBox3" }; //If you have more than the three comboBoxes
foreach(Control cb in this.Controls)
{
if(cb is ComboBox)
{
if(foods.Contains((ComboBox)cb.Text) && cbNames.Contains((ComboBox)cb.Name))
//Only use the second condition if you have more than the three comboBoxes
isvalid++;
else
(ComboBox)cb.Text = "Wrong Input";
}
}
if (isvalid == 3)
return true;
return false;
这使用foreach
,cb
来自int isvalid = 0;
List<string> foods = new List<string> { "Cheese", "Vegetable", "Meat" };
foreach(ComboBox cb in ComboBoxes)
{
if(foods.Contains(cb.Text))
isvalid++;
else
cb.Text = "Wrong Input";
}
if (isvalid == 3)
return true;
return false;
,它与循环每个组合框相同,here's some more info on foreach
在您最近的编辑后,现在可以更好地使用
var map, GeoMarker;
function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);