开发者

Tackling selecting the first Item in dropdownlist and subsequent events

I have a dropdownlist on my aspx page, whi开发者_开发百科ch I bind to a datasource. I noticed that selecting the first item didn't fire the selectedindexchanged event. Setting out to look for an answer I found that the most common thing to do was put a first item in the ddl, either with an empty string or with something like "---Select---".

Great, that worked. But then I noticed that it still fired my Page_Load event. In my Page_Load event I check for a postback. If its not, it databinds to a repeater and the ddl. So what happens is that selecting the first item in the ddl skips the databinding to the repeater and ddl, and I end up with a blank page.

I first thought I could fix this by enabling viewstate, but alas. After here and there, I put the following in my code, but I really feel it looks hacky. Does anyone have a better idea?

if (!IsPostBack || RacesDropDownList.SelectedIndex == 0)
{
    PopulateControls();
}


First of all you need viewstate to be enabled. When no postback has happened, then you have to databind the dropdownlist to the datasource. Do it by simply adding the following to the Page_Load event:

if (!IsPostBack)
{
    PopulateControls();
}

Keep in mind, that the default selectedindex is always 0, and if it has changed, then a postback will happen so your original code will already skip the databinding because of the !IsPostBack condition => '|| RacesDropDownList.SelectedIndex == 0' is not needed at all.

Then later, if on any event you have to refresh the list, the usual solution is to fire the PopulateControls() function in the event handler and not in Page_Load().

For example:

protected SelectedIndexChanged(...)
{
// Do something
changeCounter++;

// Not necessary, but good to have
ClearControlsCurrentValues();

// Populate the control again
PopulateControls();
}

I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜