如何在codebehind中引发列表控件SelectedIndexChanged事件?

Out*_*uch 3 c# asp.net

如何使用C#在代码隐藏中引发asp.net List控件的SelectedIndexChanged事件?

Aar*_*ght 15

如果你问如何手动触发事件,以便它可以运行任何附加的逻辑:不要.

您的事件处理程序应该很苗条.如果需要从多个位置执行相同的操作,则将该功能提取到自己的方法中,并让事件处理程序调用该方法.例如:

private void CountryListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    UpdateStates(ListBox1.SelectedItem.Text);
}

private void UpdateStates(string country)
{
    StateListBox.DataSource = GetStates(country);
    StateListBox.DataBind();
}
Run Code Online (Sandbox Code Playgroud)

现在SelectedIndexChanged,您只需调用此事件处理程序引用的方法,而不是尝试触发事件,即

private void Page_Load(object sender, EventArgs e)
{
    UpdateStates("USA");
}
Run Code Online (Sandbox Code Playgroud)

不要在事件处理程序中放置复杂的逻辑,并尝试从意外的位置引发这些事件.相反,将复杂逻辑放在自己的方法中,以便您可以从其他地方执行相关操作.