在定制控件中以下一段精简的代码
****************************
private Button nextButton;
private DropDownList selectList;
protected override void CreateChildControls()
{
nextButton=new Button();
selectList=new DropDownList();
for(int i=1;i<=this.PageCount ;i++)
{
ListItem item=new ListItem(i.ToString());
this.goRecord.Items.Add(item);
}
this.nextButton.Click +=new EventHandler(nextButton_Click);
this.selectList.SelectedIndexChanged +=new EventHandler(selectList_SelectedIndexChanged);
Controls.Add(nextButton);
Controls.Add(selectList);
}
private void nextButton_Click(object sender, EventArgs e)
{
this.NewPageIndex++;//一个已声明的int,并保存在ViewState
this.goRecord.Items[this.NewPageIndex].Selected =true;
}
private void selectList_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.CurrentPagerIndex ==this.NewPagerIndex)//CurrentPagerIndex一个已声明的int,并保存在ViewState
return;//如果页码没有改变则不会激发事件
this.CurrentPagerIndex =this.NewPagerIndex ;
OnPageChanged(new myEventArgs(this.CurrentPagerIndex ));//OnPageChanged一个自定义事件
}
***************************************************
我的想法是单击nextButton按钮时更改下拉框selectList的选择项从而激发selectList_SelectedIndexChanged.和直接改变selectList的选项激发自定义事件. 可是调试时它并不激发此事件.为什么?怎样更改?
我在<<Asp.Net 高级编程>>的P859 看到"在Html中只button和imagebutton元素能够引起回送的发生."
那么如搜狐的同学录中当选取地区...这些单选按钮时为什么会引起回送呢?
changing the SelectedIndex in the code will not trigger SelectedIndexChangeds event, the event will only be triggered when the dropdownlist finds that the selectedindex is different in its IPostBackDataHandler.LoadPostData method and then raises the event through IPostBackDataHandler.RaisePostDataChangedEvent
in your case, you could just call the method, after all, you are changing the SelectedIndex, you should be responsible to call SelectedIndexChanged method
private void nextButton_Click(object sender, EventArgs e)
{
this.goRecord.SelectedIndex =NewPageIndex;
selectList_SelectedIndexChanged(this.goRecord,e);
}
or you could do that on the client, when the user clicks on the button, it changes the selection of the dropdownlist, something like
protected override void CreateChildControls()
{
nextButton=new Button();
selectList=new DropDownList();
for(int i=1;i<=this.PageCount ;i++)
{
ListItem item=new ListItem(i.ToString());
this.goRecord.Items.Add(item);
}
Controls.Add(nextButton);
Controls.Add(selectList);
this.selectList.SelectedIndexChanged +=new EventHandler(selectList_SelectedIndexChanged);
//no need the following
// this.nextButton.Click +=new EventHandler(nextButton_Click);
//but use this:
this.nextButton.Attributes["onclick"] = String.Format("javascript: document.getElementById({0}).selectedIndex++;", selectList.ClientID);
}
重载一次其事件响应或者加个事件委托。