[英]how to get the previously selected index of combo box in c#
我有这个事件来更改组合框的索引;
DialogResult Result = MessageBox.Show("something", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (Result == DialogResult.No)
{
// the code write follow
}
if (Result == DialogResult.Yes)
{
NotGrazingradioButton.Checked = true;
if (CowTypeSelect.SelectedIndex == 0)
{
CowTypeDefaults.LactatingCow(this);
CowTypeVarlbl.Text = "گاو شیری";
}
else if (CowTypeSelect.SelectedIndex == 1)
{
CowTypeDefaults.DryCow(this);
CowTypeVarlbl.Text = "گاو خشک";
}
问题是,当用户单击无按钮时,新索引仍显示在组合框上,但未选中,
我在另一个事件中为先前选择的索引定义一个变量,如下所示:
public int CowTypeSelect_SelectionChangeCommitted(object sender, EventArgs e)
{
int PrevIndex = CowTypeSelect.SelectedIndex;
return PrevIndex;
}
现在我想使用此变量将combobox索引更改为这样的预览索引,但是此代码不起作用,我也不知道为什么
if (Result == DialogResult.No)
{
CowTypeSelect.SelectedIndex = CowTypeSelect_SelectionChangeCommitted.PrevIndex;
}
现在,如果假定这些没有按钮的代码起作用,那么它将成为另一个问题,因为它选择了一个索引,并且现在代码再次运行,并且与组合框的索引相关的文本框的值恢复为默认值:(
我读了很多关于我的问题的话题,但我无法弄清楚。
我想这就是您想要的:
private int prev_index = -1;
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
DialogResult Result = MessageBox.Show
("somthing",MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (Result == DialogResult.No)
{
CowTypeSelect.SelectedIndex = prev_index;
return;
}
else if (Result == DialogResult.Yes)
{
NotGrazingradioButton.Checked = true;
if (CowTypeSelect.SelectedIndex == 0)
{
CowTypeDefaults.LactatingCow(this);
CowTypeVarlbl.Text = "گاو شیری";
}
else if (CowTypeSelect.SelectedIndex == 1)
{
CowTypeDefaults.DryCow(this);
CowTypeVarlbl.Text = "گاو خشک";
}
}
prev_index = CowTypeSelect.SelectedIndex;
}
我来自您所问的上一个问题 ,似乎您对Windows Form
相当Windows Form
。 但是,由于您自己尝试过,所以使回答的人感觉更好。
添加一个全局变量LastIndex
用于存储最后一个经过验证的索引。
添加一个全局变量InhibitIndexChange
来检查用户是否触发了索引更改事件。 有关此的更多信息,请参见取消ListBox SelectedIndexChange事件。
在处理您希望在IndexChangedEvent
期间执行的代码之前,请检查InhibitIndexChange
检查消息框结果,如果为No
,则应回滚所选索引,否则,将其更新为最新索引。
完整代码
int LastIndex = -1;
bool InhibitIndexChange = false;
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
if(InhibitIndexChange)
return;
DialogResult Result = MessageBox.Show("Type text here", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (Result == DialogResult.No)
{
if(LastIndex != -1)
{
InhibitIndexChange = true;
CowTypeSelect.SelectedIndex = LastIndex;
InhibitIndexChange = false;
}
return;
}
NotGrazingradioButton.Checked = true;
if (CowTypeSelect.SelectedIndex == 0)
{
CowTypeDefaults.LactatingCow(this);
CowTypeVarlbl.Text = "گاو شیری";
}
else if (CowTypeSelect.SelectedIndex == 1)
{
CowTypeDefaults.DryCow(this);
CowTypeVarlbl.Text = "گاو خشک";
}
LastIndex = CowTypeSelect.SelectedIndex;
}
if (FirstRun == true)
{
// Codes here execute at the first time only.
...
LastIndex = CowTypeSelect.SelectedIndex;
FirstRun = false;
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.