我正在使用C#.net中的Windows窗体。
我在表单上有2 ComboBox
和3 TextBox
。当我更改ComboBox1
中的值时(通过与UI中的项目进行交互),它会更改ComboBox2
中的项目和所选项目。
当所选的ComboBox2
索引发生更改时,应该更改所有TextBox
中的文字,但似乎SelectedIndexChanged
不是被解雇了。
public void comboSelectionChanged(object sender, EventArgs e)
{
//when the selection changes...
// 1) cast the sender as a comboBox
ComboBox cBox = (ComboBox)sender;
// 2) identify the sender
if (cBox.Name.ToString() == "ComboBox1")
{ //this is the 1st combo box
//load the children of the new selection into the form
//child of ComboBox1 is ComboBox2
ComboBox2.Items.Clear();
ComboBox2.Text = null;
string selected = null;
foreach (string item in {"box2_item1","box2_item2"})
{
ComboBox2.Items.Add(item);
}
//need to set the selection last, because this will (hopefully) fire the selection changed event on the child
if (selected != null)
{//here I am actually getting the selected item from XML
ComboBox2.SelectedItem = selected;
}
else
{//this should be action that is initiated, which should definitely change the selected index
ComboBox2.SelectedIndex = -1;
}
}
else if (cBox.Name.ToString() == "ComboBox2")
{ //this is the 2nd combobox
//load the children of the new selection into the form
//the textBoxes are the children
TextBox1.Text = "some new text that I am getting from XML";
TextBox2.Text = "some other new text as above.";
TextBox3.Text = "same thing, one more time" ;
}
else
{ //I messed something up, because the combobox name is invalid
Debug.Write("Unreachable code encountered: The combobox name {" + cBox.Name.ToString() + "} is not valid!");
return;
}
我试图简化这一点,希望我没有通过简化来过度使用它。如上所述,我从XML文件获取数据,理想情况下的目标是使用此表单来读取和写入XML文件。在我看来,所有的XML工作正常,所以我把所有这些都留下了。
两个方框' SelectedIndexChanged
个事件与上面的代码相关联。会发生什么变化是当我更改ComboBox1
的值时ComboBox2
的值被更改,并且所选项目被清除,但ComboBox2.SeletedIndexChanged
事件永远不会被触发(breakpoins告诉我代码永远不会重新输入时钟),因此TextBox
没有更新新数据。
我希望一切都有道理,而且somone可以帮助我弄清楚我做错了什么。
答案 0 :(得分:0)
事件处理程序只是一种方法,因此您可以调用它。如果您的处理程序名为ComboBox2_SelectedIndexChanged
,则可以执行以下操作:
...
else
{//this should be action that is initiated, which should definitely change the selected index
ComboBox2.SelectedIndex = -1;
ComboBox2_SelectedIndexChanged(ComboBox2, new EventArgs());
}
...
答案 1 :(得分:0)
通过调用
在comboSelectionChanged(object sender, EventArgs e)
方法中通过自己触发SelectedIndexChanged事件
ComboBox2_SelectedIndexChanged(ComboBox2, new EventArgs());