I have a weird behavior in my combobox. I have two combobox, one is cboSede an the other is cboGroup. CboSede enable cboGroup. I have already done this in other forms but here I get this message: ArgumentOutOfRangeException was unhandled by user code. The idea is if the user does not choose any value in cboSede then cboGroup is not enabled and in the other hand, if the user choose a valid option in cboSede, cboGroup is enable.
This is my code:
The SelectedIndexChanged of cboSede
private void cboSede_SelectedIndexChanged(object sender, EventArgs e)
{
if (Util.Security.ConexionBD)
{
if (Convert.ToInt32(cboSede.SelectedIndex) == 0 || Convert.ToInt32(cboSede.SelectedIndex) == -1)
{
cboGroup.Enabled = false;
cboGroup.SelectedIndex = 0;
}
else
{
this.FillGroupCombo();
cboGroup.Enabled = true;
}
}
else
MessageBox.Show("Error", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
the FillGroupCombo function
private void FillGroupCombo()
{
try
{
Entity.Group objGroup = new Entidad.Group ();
objGroup .IdSede = Convert.ToInt32(cboSede.SelectedValue);
objGroup = Control.Group.ListBySede(objGroup );
if (objGroup != null && objGroup.ListGroup.Count > 0)
{
Entity.Group objMsje = new Entity.Group();
objMsje.IdGroup = -1;
objMsje.Name= "--- Select group ---";
objGroup.ListGroup.Insert(0, objMsje);
}
else
{
Entity.Group objMsje = new Entity.Group();
objMsje.IdGroup = 0;
objMsje.Name= "-- No groups found --";
objGroup.ListGroup.Insert(0, objMsje);
}
Util.Utilitario.FillCombo(objGroup.ListGroup, this.cboGroup, "IdGrupo", "Name");
}
catch (Exception ex)
{
Util.Security.Insert(ex);
Util.Security.SaveLog(ex.Message);
}
}
Any idea about why this happens?
This one
if (Convert.ToInt32(cboSede.SelectedIndex) == 0 || Convert.ToInt32(cboSede.SelectedIndex) == -1)
{
cboGroup.Enabled = false;
cboGroup.SelectedIndex = 0;
}
Will kill the code when SelectedIndex == -1
and you actually have no item in your comboBox
(when index = 0
, it is OutOfRange
)
you can give an if
condition if you want
if (cboGroup.Items.Count > 0)
cboGroup.SelectedIndex = 0;
This way, it first check of the comboBox
really have anything. And if it doesn't then it won't produce OutOfRange
error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.