pmichna
pmichna

Reputation: 4888

OnSelectedIndexChanged event won't fire for the first element of DropDownList

I have a DropDownList and the method for OnSelectedIndexChanged event changes the content of one label. It works fine except for the first element of the DropDownList. Any ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newsletter.DAL;
using Newsletter.Services;

public partial class Senders : System.Web.UI.Page
{
    private SenderService _client;
    private List<Sender> _allSenders;
    private DropDownList _dropDownListSenders;
    private TextBox _emailBox;
    private string _selectedSender;

    protected void Page_Load(object sender, EventArgs e)
    {
        _client = new SenderService();
        _allSenders = _client.GetAllSenders();
        _dropDownListSenders = (DropDownList)loginViewMain.FindControl("DropDownListSenders");
        _emailBox = (TextBox)loginViewMain.FindControl("textBoxEmail");
    }

 protected void DropDownListSenders_SelectedIndexChanged(object sender, EventArgs e)
    {
        _selectedSender = _dropDownListSenders.SelectedValue;
        _emailBox.Text = _selectedSender;
    }
}

Upvotes: 0

Views: 2584

Answers (4)

Dhananjay Shakyawar
Dhananjay Shakyawar

Reputation: 1

Please check your first item if it is set to Empty string (i.e. string.Empty). If so, then set it to null. This should resolve your problem.

Issue with Empty string : - Event does not consider changing empty string to something new as changed. whereas if you set it to null, it says null has been changed to string value. Hope this helps! Happy coding...

Upvotes: 0

syed mohsin
syed mohsin

Reputation: 2938

Your 1st element is already selected that's why when you select the 1st element again its OnSelectedIndexChanged wont fire because you are not changing the element.
OnSelectedIndexChanged will only fire if your selected element is changed.

Upvotes: 0

pmichna
pmichna

Reputation: 4888

I added ViewStateMode="true" to the DropDownList and now it works fine.

Upvotes: 1

Michael Richardson
Michael Richardson

Reputation: 4282

Do you have an 'empty' item before the first item? If not, then selecting the first item will not change the selected index (the first item was already selected) and the event will not fire.

Upvotes: 1

Related Questions