【发布时间】:2015-03-07 00:12:49
【问题描述】:
我正在使用 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 事件永远不会被触发(断点告诉我代码时钟永远不会重新输入),因此TextBox 中的任何一个都不会更新为新数据。
我希望一切都说得通,有人可以帮助我找出我做错了什么。
【问题讨论】:
-
我看不出这些 ComboBox 共享同一个事件处理程序的理由。他们似乎没有共享任何通用代码。不确定您的
selected变量在此代码中的作用。看起来很没有意义。 -
@Crowcoder + Med.Amine.Touil 谢谢你们!我不知道为什么我没有想到!我不知道为什么该事件不会自行触发,但这肯定是一种功能性解决方法!
-
@LarsTech 感谢您的意见。这里还有很多事情要做,两个组合框最终会对它们各自的孩子做同样的事情,因此希望避免冗余代码,并且都使用相同的事件处理程序。
标签: c# winforms combobox selectedindexchanged