我想在组合框更改后清除组合框。
例如,如果我有组合框1,2和3,如果2已更改,则清除3的内容。
我有点坚持这个逻辑。我应该创建一个递归方法来做这样的事情吗?或者只是使用“selectedindexchanged”事件?对此的任何想法都会有很大的帮助。
答案 0 :(得分:1)
我不确定您是使用MVVM模式,还是使用Web或桌面(winforms或wpf)应用程序,因此我将避免使用特定于技术的内容。
一种方法可能是实现每个文本框的textchanged事件并处理与每个文本框关联的逻辑。例如: texbox.textchange事件已被触发 - >因此明文(textbox2)。
答案 1 :(得分:1)
将组合框订阅到同一事件
bool _ignore;
private void comboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
// ignore event if programmatic change
if(_ignore)
return;
_ignore = true;
// instead of push/pop can be 3 if
var index = (sender as ComboBox).SelectedIndex; // push
comboBox1.SelectedIndex = comboBox2.SelectedIndex = comboBox3.SelectedIndex = -1;
(sender as ComboBox).SelectedIndex = index; // pop
_ignore = false;
}
答案 2 :(得分:0)
试试这个:
int maxNo = 4; //you can change this no and logic works till 9 comboboxes
void clearPreceding(ComboBox cmbBox)
{
int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1));
for (int i = cmbBoxNo; i <= maxNo; i++)
{
((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = "";
}
}
您可以为所有Combobox的SelectedIndexChanges
活动订阅One EventHandler,如下所示:
comboBox1.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
并且EventHandler是:
private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e)
{
clearPreceding((ComboBox)sender);
}
完整代码:
public partial class Form1 : Form
{
int maxNo = 4;
public Form1()
{
InitializeComponent();
comboBox1.SelectedIndexChanged+=AllCombobox_SelectedIndexChanged;
comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
}
private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e)
{
clearPreceding((ComboBox)sender);
}
void clearPreceding(ComboBox cmbBox)
{
int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1));
for (int i = cmbBoxNo; i <= maxNo; i++)
{
((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = "";
}
}
}